Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Unique list from QuerySet

I have a filtered QuerySet which has a ManyToMany field 'Client'. I want to create a unique dict of all the Client objects in the query set so:

Projects Queryset: - Project1.client = <Client: 1> - Project2.client = <Client: 1> - Project3.client = <Client: 2> - Project4.client = <Client: 2> - Project5.client = <Client: 3>  class Project(models.Model):     client = models.ForeignKey(Client, blank=True, null=True) 

I want to end up with a dict of client objects:

{<Client: 1>,<Client: 2>,<Client: 3>} 

Some help would be appreciated :)

like image 892
Hanpan Avatar asked Apr 20 '11 09:04

Hanpan


People also ask

How do I get unique QuerySet in Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.

How do I select unique values in Django?

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order. For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don't specify an order, you'll get some arbitrary row.


1 Answers

Project.objects.values('client').distinct() 

Link to Django docs on queryset distinct() method

like image 51
Yuval Adam Avatar answered Sep 22 '22 04:09

Yuval Adam