[django] Select DISTINCT individual columns in django?

I'm curious if there's any way to do a query in Django that's not a "SELECT * FROM..." underneath. I'm trying to do a "SELECT DISTINCT columnName FROM ..." instead.

Specifically I have a model that looks like:

class ProductOrder(models.Model):
   Product  = models.CharField(max_length=20, promary_key=True)
   Category = models.CharField(max_length=30)
   Rank = models.IntegerField()

where the Rank is a rank within a Category. I'd like to be able to iterate over all the Categories doing some operation on each rank within that category.

I'd like to first get a list of all the categories in the system and then query for all products in that category and repeat until every category is processed.

I'd rather avoid raw SQL, but if I have to go there, that'd be fine. Though I've never coded raw SQL in Django/Python before.

The answer is


The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.


It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4


User order by with that field, and then do distinct.

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-models

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries "Post Image data using POSTMAN" What does on_delete do on Django models? Django values_list vs values What's the difference between select_related and prefetch_related in Django ORM? Django Model() vs Model.objects.create() 'NOT NULL constraint failed' after adding to models.py django - get() returned more than one topic How to convert Django Model object to dict with its fields and values? How do I make an auto increment integer field in Django?

Examples related to distinct

Using DISTINCT along with GROUP BY in SQL Server How to "select distinct" across multiple data frame columns in pandas? Laravel Eloquent - distinct() and count() not working properly together SQL - select distinct only on one column SQL: Group by minimum value in one field while selecting distinct rows Count distinct value pairs in multiple columns in SQL sql query distinct with Row_Number Eliminating duplicate values based on only one column of the table MongoDB distinct aggregation Pandas count(distinct) equivalent

Examples related to django-queryset

Django values_list vs values Get the latest record with filter in Django How to do a less than or equal to filter in Django queryset? How can I filter a Django query with a list of values? How to obtain a QuerySet of all rows, with specific fields for each one of them? How to perform OR condition in django queryset? Getting a count of objects in a queryset in django How do I filter query objects by date range in Django? How to remove all of the data in a table using Django Select DISTINCT individual columns in django?

Examples related to django-orm

Django values_list vs values What's the difference between select_related and prefetch_related in Django ORM? Django: List field in model? How to convert Django Model object to dict with its fields and values? Chaining multiple filter() in Django, is this a bug? How to perform OR condition in django queryset? Django database query: How to get object by id? Select DISTINCT individual columns in django? Select distinct values from a table field