Reputation: 5850
I have a list of django model instances, however, some of them might be duplicate, how to get a list which all instances are distinct?
This is not a queryset, but a list, like:
instances = [instance1, instance2, ...]
What can I do to instances to guarantee all instances are unique?
Upvotes: 2
Views: 994
Reputation: 8250
You can use Django ORM's .distinct()
method to return distinct model objects.
Upvotes: 0
Reputation: 6733
You can use a set conversion if you want to use the inherent equality of the objects:
instances = list(set(instances))
If you want to make them unique based on a property (say name
), using a dictionary comprehension is one way to do it:
instances = { i.name: i for i in instances }.values()
Upvotes: 1