Django比较模型实例的相等性 [英] Django comparing model instances for equality
问题描述
我明白,在单身情况下,您可以执行以下操作:
I understand that, with a singleton situation, you can perform such an operation as:
spam == eggs
如果垃圾邮件
和蛋
是具有所有相同属性值的同一类的实例,它将返回 True
。在Django模型中,这是很自然的,因为模型的两个独立实例不会一样,除非它们具有相同的 .pk
值。
and if spam
and eggs
are instances of the same class with all the same attribute values, it will return True
. In a Django model, this is natural because two separate instances of a model won't ever be the same unless they have the same .pk
value.
这样做的问题是,如果对实例的引用具有已被中间件更新到某处的属性,并且尚未保存,并且您尝试使用另一个当变量保存对同一模型的实例的引用时,它将返回 False
,因为它们对某些属性具有不同的值。显然我不需要像单身人士这样的东西,但是我想知道是否有一些官方的Djangonic(ha,一个新词)方法,或者如果我应该简单地检查 .pk
的值是否相同:
The problem with this is that if a reference to an instance has attributes that have been updated by middleware somewhere along the way and it hasn't been saved, and you're trying to it to another variable holding a reference to an instance of the same model, it will return False
of course because they have different values for some of the attributes. Obviously I don't need something like a singleton , but I'm wondering if there some official Djangonic (ha, a new word) method for checking this, or if I should simply check that the .pk
value is the same with:
spam.pk == eggs.pk
对不起如果这是一个巨大的浪费时间,但它似乎可能会有一个这样做的方法,我失踪的东西,如果我没有找到,我会后悔的路。
I'm sorry if this was a huge waste of time, but it just seems like there might be a method for doing this, and something I'm missing that I'll regret down the road if I don't find it.
你应该忽略这个问题的第一部分,因为你不应该比较单身与 ==
,而是是
。单身人士真的与这个问题无关。
You should disregard the first part of this question, since you shouldn't compare singletons with ==
, but rather with is
. Singletons really have nothing to do with this question.
推荐答案
从 django文档:
要比较两个模型实例,只需使用标准的Python比较运算符,double等于sign = ==。在幕后,比较了两个模型的主键值。
To compare two model instances, just use the standard Python comparison operator, the double equals sign: ==. Behind the scenes, that compares the primary key values of two models.
这篇关于Django比较模型实例的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!