Django
What's the difference between `values()`, `values_list()`, and model instances?
Short Answer
What each row is turned into, and how many columns are fetched to build it. A plain queryset selects every concrete column and constructs a model instance per row, so the result carries your methods, properties, and save(). values() selects only the fields you name and yields plain dicts; values_list() yields tuples of the same data, or bare scalars with flat=True. All three are still querysets — lazy, chainable, sliceable — and the choice is between paying for model construction and keeping model behaviour. One rule catches people out: values() placed before annotate() stops being a projection and becomes a GROUP BY.
How It Works
A plain queryset compiles to SELECT over every concrete field on the model, and for each row returned Django builds an instance: it allocates the object, populates its fields, and records enough state for save() to know it exists. That construction is what makes shipment.is_heavy or shipment.save() possible, and it is also the cost you avoid when you do not need them.
values() changes both halves. Naming fields narrows the SELECT list to those columns, so less data crosses the connection, and each row becomes a dict rather than a model instance — no class, no methods, no save(). values_list() does exactly the same query and packs each row into a tuple instead; flat=True unwraps single-field rows to bare values, and named=True yields lightweight named tuples when you want attribute access without a model.
Between the two extremes sits only(). It returns real model instances but narrows the initial SELECT, deferring the rest. The instance keeps every method, and touching a field that was not loaded issues another query for it — per instance. That makes only() right when you need behaviour on a few fields and wrong when you will end up touching the rest anyway.
The annotate() interaction is the part worth memorising. On its own, values("status") is a projection: one dict per row. Followed by annotate(), Django reads it as a grouping key instead and emits GROUP BY, so you get one row per distinct value with the aggregate attached. The same call means "which columns" in one position and "group by these" in another, and the order decides which.
Seeing It Run
These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:
python3 main.py
Same rows, four shapes, different columns
One ordered queryset rendered every way, then the SQL each form generates.
# depot/models.py
from django.db import models
class Shipment(models.Model):
reference = models.CharField(max_length=20)
status = models.CharField(max_length=20)
weight_kg = models.IntegerField()
def __str__(self):
return self.reference
@property
def is_heavy(self):
return self.weight_kg > 200
# bootstrap.py
import django
from django.conf import settings
settings.configure(
DEBUG=True,
INSTALLED_APPS=["depot"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
DEFAULT_AUTO_FIELD="django.db.models.AutoField",
USE_TZ=False,
)
django.setup()
from django.db import connection
from depot.models import Shipment
def seed():
with connection.schema_editor() as editor:
editor.create_model(Shipment)
Shipment.objects.create(reference="SHP-3157", status="booked", weight_kg=90)
Shipment.objects.create(reference="SHP-4408", status="held", weight_kg=340)
Shipment.objects.create(reference="SHP-4471", status="booked", weight_kg=120)
connection.queries_log.clear()
# main.py
from bootstrap import Shipment, connection, seed
seed()
ordered = Shipment.objects.order_by("reference")
print("instances :", type(ordered[0]).__name__, "->", ordered[0])
print("values() :", ordered.values("reference", "status")[0])
print("values_list() :", ordered.values_list("reference", "status")[0])
print("values_list flat :", ordered.values_list("reference", flat=True)[0])
print("values_list named:", ordered.values_list("reference", "status", named=True)[0])
connection.queries_log.clear()
list(Shipment.objects.values("reference"))
print("columns for values('reference'):", connection.queries[-1]["sql"])
connection.queries_log.clear()
list(Shipment.objects.all())
print("columns for instances :", connection.queries[-1]["sql"])
instances : Shipment -> SHP-3157
values() : {'reference': 'SHP-3157', 'status': 'booked'}
values_list() : ('SHP-3157', 'booked')
values_list flat : SHP-3157
values_list named: Row(reference='SHP-3157', status='booked')
columns for values('reference'): SELECT "depot_shipment"."reference" AS "reference" FROM "depot_shipment"
columns for instances : SELECT "depot_shipment"."id", "depot_shipment"."reference", "depot_shipment"."status", "depot_shipment"."weight_kg" FROM "depot_shipment"
The same filter and ordering produce four different Python shapes from what is nearly the same query. The two SQL statements show the other half of the difference: values("reference") selects one column, while the instance form selects all four, including the id you did not ask for and the weight_kg you may never read. named=True is the middle option when tuples are too positional — attribute access without building a model.
Try it: Add print(ordered.values_list("reference", "status", flat=True)[0]) at the end: two fields and flat=True. What could a "flat" result with two columns even mean? Django refuses to guess: TypeError: 'flat' is not valid when values_list is called with more than one field. flat=True unpacks one-element tuples; with two columns there is no single value per row to return.
Dicts have no model behaviour
Replace main.py. The model defines an is_heavy property; here is who can use it.
# main.py
from bootstrap import Shipment, connection, seed
seed()
shipment = Shipment.objects.order_by("reference").first()
print("instance.is_heavy:", shipment.is_heavy)
row = Shipment.objects.order_by("reference").values("reference", "weight_kg").first()
print("values() gives :", sorted(row))
try:
row.is_heavy
except AttributeError as exc:
print("row.is_heavy ->", type(exc).__name__)
connection.queries_log.clear()
narrow = Shipment.objects.order_by("reference").only("reference").first()
print("only() returns :", type(narrow).__name__, "after", len(connection.queries), "query")
print("narrow.is_heavy :", narrow.is_heavy, "after", len(connection.queries), "queries")
instance.is_heavy: False
values() gives : ['reference', 'weight_kg']
row.is_heavy -> AttributeError
only() returns : Shipment after 1 query
narrow.is_heavy : False after 2 queries
The dict holds weight_kg, the exact data is_heavy needs, and still cannot answer the question — the property lives on the class, and a dict has no class of yours. This is the trade in one line: values() is cheaper because it skips building the thing that knows how to behave. only() shows the third position — a real Shipment from a narrowed SELECT, which answers is_heavy correctly but pays a second query to fetch the deferred weight_kg. Do that in a loop and the saving becomes a per-row round trip.
values() before annotate() means GROUP BY
Replace main.py. The same values() call, now followed by an aggregate.
# main.py
from bootstrap import Shipment, connection, seed
from django.db.models import Count
seed()
per_status = Shipment.objects.values("status").annotate(total=Count("id")).order_by("status")
print("rows:", list(per_status))
print("SQL :", connection.queries[-1]["sql"])
rows: [{'status': 'booked', 'total': 2}, {'status': 'held', 'total': 1}]
SQL : SELECT "depot_shipment"."status" AS "status", COUNT("depot_shipment"."id") AS "total" FROM "depot_shipment" GROUP BY 1 ORDER BY 1 ASC
Three shipments produce two rows. values("status") on its own would have given one dict per shipment; placed before annotate(), it became the grouping key and the query grew a GROUP BY. That is the whole aggregation idiom in Django — the fields you project are the fields you group by — and it is why adding a field to a values() call that precedes annotate() silently changes the granularity of the result rather than just adding a column. Putting annotate() first instead annotates each row individually and groups nothing.
Try it: Swap the order of the two calls: Shipment.objects.annotate(total=Count("id")).values("status").order_by("status"). Same methods, same arguments; do you still get two groups? No: rows has three dictionaries, booked, booked, held, with no total, and the GROUP BY lists the shipment's id and its other columns. values() placed before annotate() chooses the grouping columns; placed after, it only chooses which columns to show from a grouping already done per row.
Edge Cases and Gotchas
values()can traverse relations.values("carrier__name")follows the foreign key and adds a join, giving a flat dict with data from two tables — something a model instance can only reach by loading the related object.values_list(flat=True)accepts exactly one field. Two fields withflat=TrueraisesTypeError; usenamed=Trueor plain tuples for more.- The result is still a queryset.
values()output can be filtered, ordered, and sliced afterwards, and is still lazy — but it can no longer be used where a model instance is expected, includingsave()and most template model helpers. only()anddefer()are per instance, not per queryset. Touching a deferred field costs one query for that object, so a loop over a hundred narrowed instances can pay a hundred extra queries.- Aggregating without
values()collapses everything.Shipment.objects.aggregate(Count("id"))returns a single dict for the whole queryset;values(...).annotate(...)is what produces one row per group.
Summary
A queryset that returns model instances selects every column and builds an object per row; values() and values_list() narrow the columns and skip the object, returning dicts or tuples. Choose by whether you need model behaviour downstream, and remember that values() changes meaning when an annotate() follows it.
- Model instances carry methods, properties, and
save(), at the cost of selecting every concrete column and constructing an object per row. values()yields dicts andvalues_list()tuples from the same narrowed query;flat=Trueunwraps a single field andnamed=Truegives attribute access without a model.- A dict cannot use a model property even when it holds the underlying data, because the behaviour lives on the class.
only()returns real instances from a narrowedSELECT, but reading a deferred field costs an extra query per instance.values()followed byannotate()becomes theGROUP BYkey, so the fields you project decide the granularity of the result.