Django查询单下划线的行为类似于双下划线



我最近在代码中犯了一个拼写错误,并注意到我得到了相同的行为,所以我想知道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_idMyModel的(隐藏)字段名,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)

由于underscoredouble_underscore在内存中是独立的对象,我相信这就是underscore == double_underscore返回False的原因。

相关内容

最新更新