Skip to content

Getting "Cannot resolve keyword 'author' into field" after annotating with QS function #2917

@torarvid

Description

@torarvid

Bug report

What's wrong

Not sure if this is django-stubs or mypy or what, but basically if I bump django-stubs from 5.2.2 to .3 or larger, I get mypy errors for keywords in filter() calls if the keyword is annotated inside of a function inside of a queryset method. I guess an example will illustrate better, so here goes:

from typing import Self

from django.db.models import CharField, Manager, Model, QuerySet


class BookQuerySet(QuerySet["Book"]):
    def annotate_author(self) -> Self:
        return self.annotate(author="blah")


class Book(Model):
    title: CharField[str, str] = CharField[str, str]()
    objects: Manager["Book"] = Manager["Book"].from_queryset(BookQuerySet)()


def foo() -> None:
    qs: BookQuerySet = Book.objects.all()
    qs.filter(foo="bar").count()  # Error 'misc'; as intended
    qs.annotate(foo=123).filter(foo=123).count()  # Ok; as intended
    qs.annotate_author().filter(author="blah").count()  # Error 'misc' <-- bug, IMO

When I run mypy on it, I get this:

❯ uv run mypy .
somesite/models.py:18: error: Cannot resolve keyword 'foo' into field. Choices are: id, title  [misc]
somesite/models.py:20: error: Cannot resolve keyword 'author' into field. Choices are: id, title  [misc]
Found 2 errors in 1 file (checked 7 source files)

So the line 18 error is expected in my head, since 'foo' is not a prop or an annotation. Line 19 does an explicit annotation inline, so mypy is happy there. But on 20, the .annotate_author call returns Self. To me it is doing "the same as the annotation on line 19, but wrapped in a queryset method".

How is that should be

I expected:

❯ uv run mypy .
somesite/models.py:18: error: Cannot resolve keyword 'foo' into field. Choices are: id, title  [misc]
Found 1 errors in 1 file (checked 7 source files)

As mentioned in the intro, I'm not sure if this is just a mypy limitation, but since I noticed it after django-stubs 5.2.3+, I'm reporting it here 🤷🏼‍♂️

System information

  • OS:
  • python version: 3.13.7
  • django version: 5.2.8
  • mypy version: 1.18.2
  • django-stubs version: 5.2.7
  • django-stubs-ext version: 5.2.7

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