0
0
DjangoHow-ToBeginner · 3 min read

How to Use values() in Django QuerySet for Efficient Data Access

Use the values() method on a Django QuerySet to get a list of dictionaries containing only the specified fields instead of full model instances. This helps you fetch just the data you need, improving performance and simplifying data handling.
📐

Syntax

The values() method is called on a Django QuerySet and takes one or more field names as arguments. It returns a QuerySet of dictionaries where each dictionary contains the specified fields and their values.

Example parts:

  • Model.objects.values('field1', 'field2'): fetches only field1 and field2 from the database.
  • The result is a QuerySet of dictionaries, not model instances.
python
Model.objects.values('field1', 'field2')
💻

Example

This example shows how to use values() to get only the id and name fields from a Book model. It prints a list of dictionaries with those fields.

python
from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_year = models.IntegerField()

# Fetch only 'id' and 'name' fields
books = Book.objects.values('id', 'name')

for book in books:
    print(book)
Output
{'id': 1, 'name': 'Django Basics'} {'id': 2, 'name': 'Advanced Django'} {'id': 3, 'name': 'Python for Web'}
⚠️

Common Pitfalls

1. Expecting model instances: values() returns dictionaries, not model objects, so you cannot call model methods on the results.

2. Forgetting to specify fields: Calling values() without arguments returns all fields, which may be inefficient.

3. Mixing with other QuerySet methods: Some QuerySet methods expect model instances and may not work as expected with values() results.

python
wrong = Book.objects.values()
# This returns all fields as dictionaries, which might be large

right = Book.objects.values('id', 'name')
# This returns only needed fields, improving performance
📊

Quick Reference

MethodDescription
values('field1', 'field2')Returns dictionaries with specified fields only
values()Returns dictionaries with all fields (less efficient)
values_list('field1', flat=True)Returns a flat list of values for one field
values_list('field1', 'field2')Returns tuples of values for specified fields

Key Takeaways

Use values() to fetch dictionaries of specific fields for better performance.
values() returns dictionaries, not model instances, so no model methods are available.
Always specify fields in values() to avoid fetching unnecessary data.
Combine values() with filters to get precise data subsets.
Use values_list() if you want tuples or flat lists instead of dictionaries.