Django comparing model instances for equality

后端 未结 8 1803
夕颜
夕颜 2020-12-01 11:53

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

spam == eggs

and if spam and eggs

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:27

    It would be strange if two model instances compared as equal if they had different attributes. Most of the time that would be undesirable.

    What you want is a special case. Comparing spam.pk == eggs.pk is a good idea. If there's no pk yet, because they haven't been saved, then it's harder to define which instances are "really" the same if some attributes are different.

    How about adding a custom attribute to your instances when creating them, eg: spam.myid=1, eggs.myid=2

    That way at some point in your code when spamcopy1.seasoning=ketchup and spamcopy2.seasoning=blackpepper you can compare their myid attribute to see if they're really the "same" spam.

提交回复
热议问题