Skip to content

Django: annotate() attributes are typed Unknown instead of their expression type #5734

Open

Description

@dhruvparanjape

Describe the Bug

Since #4928, pyrefly knows the attributes that QuerySet.annotate() adds to model rows, so accessing them no longer reports missing-attribute. Their type is Unknown, though, so nothing about the value is checked: row.n_books + "x" passes.

The type is known from the expression: Count gives int, Exists gives bool, Sum over a DecimalField gives Decimal | None (None when there are no rows), and an explicit output_field decides the type when given.

Reproduction

# models.py
from django.db import models


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


class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    price = models.DecimalField(max_digits=8, decimal_places=2)
from typing import reveal_type

from django.db.models import Count, Exists, IntegerField, OuterRef, Sum

from models import Author, Book

has_books = Exists(Book.objects.filter(author=OuterRef("pk")))

for a in Author.objects.annotate(
    n_books=Count("books"),
    has_books=has_books,
    total=Sum("books__price"),
    total_int=Sum("books__price", output_field=IntegerField()),
):
    reveal_type(a.n_books)    # Unknown, expected int
    reveal_type(a.has_books)  # Unknown, expected bool
    reveal_type(a.total)      # Unknown, expected Decimal | None
    reveal_type(a.total_int)  # Unknown, expected int | None
    a.n_books + "x"           # no error reported

Expected

Annotated attributes get the type of their expression, using output_field when it is given, and Unknown only where the expression type can't be worked out.

Notes

Versions

pyrefly 1.5.0 (preset = "default"), Django 5.2, django-stubs 6.1.2, Python 3.12.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions