我最近在代码中犯了一个拼写错误,并注意到我得到了相同的行为,所以我想知道django查询中单下划线和双下划线之间的区别。
>>> 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列表时,我发现其中包含完全相同的元素。有人知道这里发生了什么吗?
这两个字段恰好都存在。
foreign_key_id
是在MyModel
对象上自动创建的列,而foreign_key__id
是外键表本身的ID。
这两个值将是相同的。。
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.
foreign_key_id
是MyModel
的(隐藏)字段名,foreign_key__id
是对foreign_key
字段引用的任何模型上的字段的引用。换句话说,它是国外关键领域的一个具体细节。
根据我的观察,Django足够聪明,如果只过滤或获取foreign_key__id
,就不会使用ForeignKey进行联接。你可以用测试
>>> print(MyModel.objects.filter(foreign_key_id=var).query)
>>> print(MyModel.objects.filter(foreign_key__id=var).query)
由于underscore
和double_underscore
在内存中是独立的对象,我相信这就是underscore == double_underscore
返回False的原因。