[django] Django values_list vs values

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.

This question is related to django django-models django-queryset django-orm

The answer is


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

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

You can get the different values with:

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

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.


Questions with django tag:

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? ImportError: No module named 'django.core.urlresolvers' How to set environment variables in PyCharm? How to get Django and ReactJS to work together? Invalid http_host header Django model "doesn't declare an explicit app_label" "Post Image data using POSTMAN" TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' Django URLs TypeError: view must be a callable or a list/tuple in the case of include() What is a NoReverseMatch error, and how do I fix it? What does on_delete do on Django models? Django values_list vs values Django download a file Uncaught TypeError: $(...).datepicker is not a function(anonymous function) Django - makemigrations - No changes detected How can I enable CORS on Django REST Framework Django - Did you forget to register or load this tag? Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet." Django Rest Framework -- no module named rest_framework How to revert the last migration? What's the difference between select_related and prefetch_related in Django ORM? Django: save() vs update() to update the database? Where does pip install its packages? no module named urllib.parse (How should I install it?) How to set the timezone in Django? You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application Django Model() vs Model.objects.create() NumPy array is not JSON serializable React Error: Target Container is not a DOM Element OperationalError, no such column. Django how to use python2.7 pip instead of default pip The view didn't return an HttpResponse object. It returned None instead You are trying to add a non-nullable field 'new_field' to userprofile without a default ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings 'NOT NULL constraint failed' after adding to models.py Django 1.7 - "No migrations to apply" when run migrate after makemigrations How to compare two JSON objects with the same elements in a different order equal? Django: OperationalError No Such Table Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet Mac OS X - EnvironmentError: mysql_config not found

Questions with django-models tag:

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? __init__() got an unexpected keyword argument 'user' How to properly use the "choices" field option in Django Django error - matching query does not exist How to create Password Field in Model Django Django DoesNotExist Get the latest record with filter in Django How can I temporarily disable a foreign key constraint in MySQL? Foreign Key Django Model Create Django model or update if exists Update only specific fields in a models.Model How to 'bulk update' with Django? How to get the currently logged in user's user id in Django? How do I get the current date and current time only respectively in Django? How to create password input field in django What is the difference between null=True and blank=True in Django? Django - how to create a file and save it to a model's FileField? How to obtain a QuerySet of all rows, with specific fields for each one of them? How to express a One-To-Many relationship in Django What's the difference between django OneToOneField and ForeignKey? matching query does not exist Error in Django Getting a count of objects in a queryset in django How to set True as default value for BooleanField on Django? Fastest way to get the first object from a queryset in django? How do I clone a Django model instance object and save it to the database? How do I filter query objects by date range in Django? Django: Display Choice Value Django database query: How to get object by id? Django request get parameters Select DISTINCT individual columns in django? How to delete a record in Django models? How to update fields in a model without creating a new record in django? Get model's fields in Django Bulk create model objects in django Automatic creation date for Django model form objects? Django: Get list of model fields? How to select a record and update it, with a single queryset in Django? how to import csv data into django models Good ways to sort a queryset? - Django Django ManyToMany filter() How to define two fields "unique" as couple

Questions with django-queryset tag:

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? Getting the SQL from a Django QuerySet How do I get the object if it exists, or None if it does not exist? How to select a record and update it, with a single queryset in Django? Select distinct values from a table field Django - filtering on foreign key properties Checking for empty queryset in Django How can I filter a date of a DateTimeField in Django? How to filter empty or NULL names in a QuerySet? How do I do an OR filter in a Django query? How do I do a not equal in Django queryset filtering? How to combine two or more querysets in a Django view?

Questions with django-orm tag:

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