Django查询单下划线是否像双下划线一样? [英] Django query single underscore behaving like double underscore?

查看:180
本文介绍了Django查询单下划线是否像双下划线一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在代码中打了一个错字,发现我得到了相同的行为,所以我想知道Django查询中单下划线和双下划线之间的区别是什么.

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

我不确定正在使用哪种相等方法比较查询集,但是当我转换为python列表时,会发现其中包含的元素完全相同.有人对这里发生的事情有一些了解吗?

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是在MyModel对象上自动创建的列,而foreign_key__id是外键表本身上的ID.

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.

这些值都将相同.

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. 

这篇关于Django查询单下划线是否像双下划线一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆