Django values_list

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance. Here’s a basic example:

>>> queryset = Book.objects.values_list('id', 'title')
<QuerySet [(1, 'Moby Dick'), (2, 'The Big Short'), ...]>

When iterated over, instead of model instances, it will contain tuples with values.

flat parameter

When grabbing a single values from the db, you can pass`flat=true` which will just give you back single values, instead of tuples:

>>> queryset = Book.objects.values_list('title', flat=True)
<QuerySet ['Moby Dick', 'The Big Short', 'The Davinci Code', ...]>

Passing flat=true with multiple values will throw an error.

named parameter

Passing named=true will give back named tuples:

>>> queryset = Book.objects.values_list('id', 'title')
<QuerySet [Row(id=1, title='Moby Dick'), Row(id=2, title='The Big Short'), ...]>
>>> for book_data in queryset:
...    print(book_data.title)

There is a small performance penalty for transforming the results into named tuples.

Using Django values_list

Standard ORM

You can use it along with other Django ORM features, like sorting, limiting, and filtering.

book_ids = Book.objects.filter(author=author_leo).values_list('id', 'title').order_by('title)

Grabbing One Value

You can also use it to conveniently grab a single value from the database:

>>> id = Book.objects.values_list('title', flat=True).get(id=3)
Moby Dick

Leave a Reply