dspjm
dspjm

Reputation: 5850

Django: How to make a list of model instances distinct?

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

Answers (2)

v1k45
v1k45

Reputation: 8250

You can use Django ORM's .distinct() method to return distinct model objects.

Upvotes: 0

nima
nima

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

Related Questions