Repository navigation
Description
Describe the Bug
QuerySet.values(...) and values_list(...) rows fall back to django-stubs' generic types, even when every field name is a literal: values() gives dict[str, Any] and values_list() gives Any. A TypedDict return annotation for the rows can't be written either, because QuerySet[M, dict[str, Any]] is not assignable to QuerySet[M, MyRow].
At runtime the shapes are fully determined by the arguments: values() yields a plain dict with exactly the named keys, values_list() a tuple, flat=True the field's value, and named=True a namedtuple (Row). A TypedDict / typed tuple would describe exactly what Django returns, with no runtime or access change (row["total"] stays the same).
Reproduction
Models as in #5734:
from typing import reveal_type
from django.db.models import Sum
from models import Book
reveal_type(Book.objects.values("author__name", "price").first())
reveal_type(Book.objects.values("author__name").annotate(total=Sum("price")).first())
reveal_type(Book.objects.values_list("author__name", "price").first())
reveal_type(Book.objects.values_list("price", flat=True).first())
reveal_type(Book.objects.values_list("author__name", "price", named=True).first())| Expression | pyrefly 1.5.0 | Expected |
|---|---|---|
values("author__name", "price") row |
dict[str, Any] |
TypedDict with author__name: str, price: Decimal |
values("author__name").annotate(total=Sum("price")) row |
dict[str, Any] |
TypedDict with author__name: str, total: Decimal | None |
values_list("author__name", "price") row |
Any |
tuple[str, Decimal] |
values_list("price", flat=True) row |
Any |
Decimal |
values_list("author__name", "price", named=True) row |
Any |
a NamedTuple with those fields |
Expected
Row types derived from literal field names, including lookups across relations (author__name) and annotated keys. Keep today's types as the fallback when the names aren't literals (values(*fields)) or can't be resolved.
Notes
- Annotated keys need the expression types requested in Django: annotate() attributes are typed Unknown instead of their expression type #5734.
- The mypy Django plugin infers
TypedDictrows forvalues().
Versions
pyrefly 1.5.0 (preset = "default"), Django 5.2, django-stubs 6.1.2, Python 3.12.
Activity