0
0
DjangoHow-ToBeginner · 3 min read

How to Use values_list in Django: Syntax and Examples

In Django, use values_list() on a QuerySet to get tuples of field values instead of full model instances. You can specify one or more fields as arguments, and use flat=True to get a simple list when querying a single field.
📐

Syntax

The values_list() method is called on a Django QuerySet. You pass the field names you want as strings. If you want a flat list for a single field, add flat=True.

  • fields: One or more field names as strings.
  • flat: Boolean, optional. Use only if querying one field to get a flat list.
python
Model.objects.values_list('field1', 'field2', flat=False)
💻

Example

This example shows how to get a list of usernames from a User model using values_list(). It also shows how to get tuples of usernames and emails.

python
from django.contrib.auth.models import User

# Get a flat list of usernames
usernames = User.objects.values_list('username', flat=True)
print(list(usernames))

# Get tuples of (username, email)
user_data = User.objects.values_list('username', 'email')
print(list(user_data))
Output
['alice', 'bob', 'carol'] [('alice', 'alice@example.com'), ('bob', 'bob@example.com'), ('carol', 'carol@example.com')]
⚠️

Common Pitfalls

Common mistakes include:

  • Using flat=True with multiple fields, which raises an error.
  • Expecting model instances instead of tuples when using values_list().
  • Not converting the QuerySet to a list before printing, which may show a QuerySet object instead of values.
python
from django.contrib.auth.models import User

# Wrong: flat=True with multiple fields causes error
# User.objects.values_list('username', 'email', flat=True)  # Raises ValueError

# Right: flat=True only with one field
usernames = User.objects.values_list('username', flat=True)
print(list(usernames))
Output
['alice', 'bob', 'carol']
📊

Quick Reference

UsageDescription
values_list('field')Returns tuples with one field each (default as tuples)
values_list('field', flat=True)Returns a flat list of values for a single field
values_list('field1', 'field2')Returns tuples with multiple fields
values_list()Returns tuples of all fields (rarely used)

Key Takeaways

Use values_list() to get tuples of specific fields from a QuerySet instead of full model instances.
Add flat=True only when querying a single field to get a simple list of values.
values_list() returns tuples by default, so expect tuples when querying multiple fields.
Always convert the QuerySet to a list to see the actual values when printing.
Avoid using flat=True with multiple fields to prevent errors.