Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

Django comparing model instances for equality

I understand that, with a singleton situation, you can perform such an operation as:

spam == eggs

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.

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, by running:

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.

UPDATE (02-27-2015)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From Django documentation:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...