Reputation: 317
I'm struggling with or query. It give me weird output. In models file i have as shown below:
class Server:
addres_ip=models.GenericIPAddressField()
class Interface:
addres_ip=models.CharField(max_length=15,default='127.0.0.1',blank=True)
server=models.ForeignKey(Server,default=None,blank=True,null=True,on_delete=models.CASCADE)
In db i have added a Server object with addres_ip='10.0.10.11' and with his Interface with addres_ip='10.1.1.2'.
When i query:
Server.objects.filter(addres_ip='10.0.10.11')
I get 1 result and it's correct
Interface.objects.filter(addres_ip='10.0.10.11')
I get 0 results and it's correct as well
but when I query:
Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11'))
i get 7 results........
Am i missing something ? there should be 1 result ..I think but not sure right now ?
Thank you in advance
Upvotes: 1
Views: 67
Reputation: 21807
There are 7 instances of Interface
having a foreign key to the Server
having addres_ip='10.0.10.11'
hence from the join (performed due to writing Interface__adress_ip='10.0.10.11'
) you get 7 (duplicated) objects / rows in the result.
Add a .distinct()
at the end of your query, to remove the duplicate results:
Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11')).distinct()
Upvotes: 2