Django values_list vs values

DjangoDjango ModelsDjango QuerysetDjango Orm

Django Problem Overview


In Django, what's the difference between the following two:

Article.objects.values_list('comment_id', flat=True).distinct()

vs

Article.objects.values('comment_id').distinct()

My goal is to get a list of unique comment ids under each Article. I've read the documentation (and in fact have used both approaches). The results overtly seem similar.

Django Solutions


Solution 1 - Django

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

Solution 2 - Django

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

Solution 3 - Django

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

Solution 4 - Django

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

> Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

> This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHassan BaigView Question on Stackoverflow
Solution 1 - DjangoAlasdairView Answer on Stackoverflow
Solution 2 - DjangoIbrahim KasimView Answer on Stackoverflow
Solution 3 - DjangopituView Answer on Stackoverflow
Solution 4 - Djangorun_the_raceView Answer on Stackoverflow