Skip to content

WithAnnotations and values or values_list #3213

@pai-martinreidemeister

Description

@pai-martinreidemeister

Bug report

What's wrong

When I annotate a query mypy complains when I try to use the annotated field in .values_list() or .values():

# app/models.py
from django.db import models


class Item(models.Model):
    name = models.CharField(max_length=100)

# repro.py
from typing import TYPE_CHECKING, TypedDict, reveal_type

from django.db.models import IntegerField, QuerySet, Value
from django_stubs_ext import WithAnnotations

from app.models import Item

class ExtraAnnotation(TypedDict):
    extra_id: int | None

if TYPE_CHECKING:
    ItemWithExtraAnnotation = WithAnnotations[Item, ExtraAnnotation]
else:
    ItemWithExtraAnnotation = Item

ItemWithExtraAnnotationQuerySet = QuerySet[Item, ItemWithExtraAnnotation]

def annotate_extra(qs: QuerySet[Item]) -> ItemWithExtraAnnotationQuerySet:
    return qs.annotate(extra_id=Value(None, output_field=IntegerField()))


qs = annotate_extra(Item.objects.all())

reveal_type(qs)
_ = qs.values_list("extra_id")
_ = qs.values("extra_id")
$ mypy
repro.py:26: note: Revealed type is "django.db.models.query.QuerySet[app.models.Item, app.models.Item@AnnotatedWith[TypedDict('repro.ExtraAnnotation', {'extra_id': builtins.int | None})]]"
repro.py:27: error: Cannot resolve keyword 'extra_id' into field. Choices are: id, name  [misc]
repro.py:28: error: Cannot resolve keyword 'extra_id' into field. Choices are: id, name  [misc]
Found 2 errors in 1 file (checked 4 source files)

How is that should be

Mypy should not raise an error when I use values or values_list with an annotated field. (see also #3207)

System information

  • OS: Linux
  • python version: 3.13.12
  • django version: 6.0.3
  • mypy version: 1.19.1
  • django-stubs version: 6.0.1 @ a9f3a8d
  • django-stubs-ext version: 6.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions