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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With