[英]remove duplicates from the list of a model instances
Based on the post: Django comparing model instances for equality 基于帖子: Django比较模型实例的相等性
I am trying to remove the duplicates from my list of instance (Which have not been saved yet and I assume their 'id' to be None) 我试图从我的实例列表中删除重复项(尚未保存,我认为他们的'id'为None)
the code is: 代码是:
a = list()
a.append(relation_list.pop())
for x in relation_list:
duplicate = False
for z in a:
if z is x:
#or if z.attrib1 == x.attrib1 and z.attrib2 == x.attrib2:
duplicate = True
if not duplicate:
a.append(x)
However, given the attribs being equal the line duplicate = True never get executed. 但是,如果attribs相等,则行duplicate = True永远不会被执行。
What am I missing? 我错过了什么?
Is there a more efficient way to achieve this? 有没有更有效的方法来实现这一目标? (inspired from this post using "in relation_list" either does not work. (灵感来自这篇文章使用“in relation_list”要么不起作用。
Try this and let me know the result: 试试这个,让我知道结果:
a = list()
for x in relation_list:
if x.attrib1 not in [z.attrib1 for z in a]:
a.append(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.