3

Based on the post: Django comparing model instances for equality

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)

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.

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.

Azee
  • 329
  • 6
  • 20
  • Can you explain how `relation_list` was populated in the first place? – Daniel Roseman Dec 24 '17 at 11:57
  • sure. I have four models. lets say Action, Criteria, Danger, and Relation. Relation stores the intensity of danger that is associated with action based on the conditions stored in criteria. So I annotate a 'Exist' field to Danger and loop through it to store the relations. (the_relation.Action_id, the_relation.Danger_id, the_relation.Intensity @DanielRoseman – Azee Dec 24 '17 at 12:12
  • Due to complexity of models and calculations 'Exist' annotation (among others) returns redundant relations which are identical. I just want to save unique values. – Azee Dec 24 '17 at 12:15
  • @Azee `z is x` can be `False` even if `z` and `x` are equal. See [this question](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python). Can you try with `==` operator instead of `is`? – xyres Dec 24 '17 at 12:30
  • @xyres I have already tried that. Nothing changes. – Azee Dec 24 '17 at 12:46

1 Answers1

2

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)
Happy Ahmad
  • 1,072
  • 2
  • 14
  • 33