Django values_list vs values

Hassan Baig picture Hassan Baig · May 13, 2016 · Viewed 150.8k times · Source

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.

Answer

Alasdair picture Alasdair · May 13, 2016

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]>