Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving distinct records based on a column on Django

I need to retrieve a list of records for the following table with distinct values in regards to name:

Class C:

name                value
A ------------------ 10
A ------------------ 20
A ------------------ 20
B ------------------ 50
C ------------------ 20
D ------------------ 10
B ------------------ 10
A ------------------ 30

I need to get rid of all the duplicate values for name and only show the following:

name                value
A ------------------ 30
B ------------------ 10
C ------------------ 20
D ------------------ 10

As you can see, it almost looks like a python set. I can probably generate the set using Python, but I'm wondering if Django's ORM has this feature.

I tried using distinct, but it doesn't accept any argument to specify which column has to have distinct values. Any idea how to get this query working?

like image 794
mohi666 Avatar asked Jan 18 '11 10:01

mohi666


1 Answers

.distinct() is the tool, but here's the syntax I had to use :

Model.objects.values_list('name', flat=True).distinct()

This way you only get a list [A,B,C,D] of values, not the objects themseleves.

like image 196
Dominique Guardiola Avatar answered Oct 17 '22 07:10

Dominique Guardiola