Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query single underscore behaving like double underscore?

I made a typo in my code recently and noticed that I got the same behavior, so I was wondering what the difference between single and double underscores are in django queries.

>>> underscore = MyModel.objects.filter(foreign_key_id=var)
>>> double_underscore =  MyModel.objects.filter(foreign_key__id=var)
>>> underscore == double_underscore
False
>>> list(underscore) == list(double_underscore)
True

I'm not sure what equality method is being used to compare the querysets, but when I convert to python lists I find exactly the same elements contained within. Does anyone have some insight into what's going on here?

like image 882
blackfedora Avatar asked Feb 18 '13 21:02

blackfedora


1 Answers

Those two fields just happen to both exist.

foreign_key_id is an automatically created column on the MyModel object, whereas foreign_key__id is the ID on the foreign key table itself.

These values would both be the same..

MyModel1.foreign_key_id == 5  # this is stored on the model
                              # and does not require a lookup.
MyModel1.foreign_key.id == 5  # this is stored on the target table
                              # and requires a DB hit. 
like image 149
Yuji 'Tomita' Tomita Avatar answered Oct 05 '22 22:10

Yuji 'Tomita' Tomita