I tried to search with Rest Framework a specific parameter in the sqlite using django but i get the following error:
return int(value)
ValueError: invalid literal for int() with base 10: '10.48.38.28'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):...
ValueError: Field 'id' expected a number but got '10.48.38.28'.
[27/Sep/2022 13:23:59] "GET /sipinterface/?ipHost=10.48.38.28/ HTTP/1.1" 500 155723
MODELS
class sipInterface(models.Model):
siRealmId=models.CharField(max_length=75)
siIpAddress=models.CharField(max_length=75)
siPort=models.IntegerField()
siTransportProtocol=models.CharField(max_length=75,null=True)
siAllowAnonymus=models.CharField(max_length=75,null=True)
ipHost = models.ForeignKey(host, on_delete=models.CASCADE)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now_add=True)
class Meta: #nombre sing y plural de musica
verbose_name="sipInterface"
verbose_name="sipInterface"
def __str__(self):
return f"{self.siRealmId},{self.siIpAddress},{self.siPort},{self.siTransportProtocol},{self.siAllowAnonymus},{self.ipHost}"
The Serializers file is the next: SERIALIZERS:
from rest_framework import serializers
from .models import sipInterface
class sipInterfaceSerializer(serializers.ModelSerializer):
class Meta:
model=sipInterface
fields=['siRealmId','siIpAddress','siPort','siTransportProtocol','siAllowAnonymus','ipHost']
The file of the view is the next: VIEW
class sipInterfaceList(generics.ListAPIView):
serializer_class=sipInterfaceSerializer
def get_queryset(self):
queryset = sipInterface.objects.all()
ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None)))
if ipHost is not None:
queryset = sipInterface.objects.filter()
queryset = queryset.filter(ipHost=ipHost) #<--- THE ERROR!
else:
queryset = []
return queryset
class sipInterfaceDetail(generics.RetrieveAPIView):
queryset=sipInterface.objects.all()
serializer_class=sipInterfaceSerializer
def get_queryset(self):
queryset = sipInterface.objects.all()
ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None)))
if ipHost is not None:
queryset = sipInterface.objects.filter()
queryset = queryset.filter(ipHost=ipHost)
else:
queryset = []
return queryset
I mark the line with the error with #<--- THE ERROR! Thanks for your help
CodePudding user response:
You have field ipHost
as ForeignKey
:
ipHost = models.ForeignKey(host, on_delete=models.CASCADE)
So if you want to filter by it, then you have to pass its pk
(id
in your case) or lookup for it's field. Let's assume that your host
model has a field ip
, then your filter should look like:
queryset = queryset.filter(ipHost__ip=ipHost)