Django查询单下划线表现得像双下划线?

bla*_*ora 3 python mysql django django-models django-queryset

我最近在我的代码中输入了一个拼写错误并注意到我有相同的行为,所以我想知道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
Run Code Online (Sandbox Code Playgroud)

我不确定使用什么相等的方法来比较查询集,但是当我转换为python列表时,我发现其中包含完全相同的元素.有没有人对这里发生的事情有所了解?

Yuj*_*ita 9

这两个领域恰好都存在.

foreign_key_idMyModel对象上自动创建的列,而是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. 
Run Code Online (Sandbox Code Playgroud)