Is there a way to counter unnecessary joins that check for id when using Django orm?

In the example. If I have a Person model that has a mother field that is a foreign key. The following gets to me:

p = Person.object.get(id=1) if p.mother_id: print "I have a mother!" 

In the above example, we issued one request. I tricked Django to not get his mother, using the _id field instead of mother.id. But if I were to filter everyone who has no mother:

 Person.objects.filter(mother=None) Person.objects.filter(mother__id=None) Person.objects.filter(mother__isnull=True) Person.objects.filter(mother__id__isnull=True) 

They are all not related to each other in a linked table .. and I cannot refer to _id columns because they are not fields .. so one of the following crashes:

 Person.objects.filter(mother_id__isnull=True) Person.objects.filter(mother_id=None) 

Is there a way to create a querySet that checks for the existence of a value in a foreign key column without a join?

Thanks in advance.

Edit (answer): The loan belongs to Bernd, who commented on Daniel's answer, but it turns out that this workaround is great for returning people without mothers without causing an unnecessary connection:

 Person.objects.exclude(mother__isnull=False) 

Edit (more):

I should also mention that I found that this behavior only seems to make it hang when FK relationships are NULL. Odd but true.

+6
python django
source share
1 answer

I was surprised by this - I thought that Person.object.filter(mother=None) would work without an additional connection, but when checking it turns out that you are right. In fact, this is logged as a bug in Django trackers.

Unfortunately, the person who registered it and who (re) wrote most of the Django request code no longer participates in Django, so I don’t know when it will actually be fixed. You can try one of the patches on this ticket and see if they help.

+3
source share

All Articles