Skip to content

5.2.3 regression: Prefetch with a related queryset produces arg-type errors with django-money #2842

@stianjensen

Description

@stianjensen

Bug report

What's wrong

Using Prefetch with a related queryset now produces arg-type errors after upgrading from django-stubs==5.2.2 to 5.2.5.

This happens only when the base model includes a MoneyField from django-money. Without MoneyField, the same code type-checks fine.

Minimal example:

from django.db import models
from django.db.models import Prefetch
from djmoney.models.fields import MoneyField

class Author(models.Model):
    name = models.CharField(max_length=100)
    # Trigger: the presence of a MoneyField
    advance = MoneyField(max_digits=10, decimal_places=2, default_currency="USD")

class Book(models.Model):
    author = models.ForeignKey(Author, related_name="books", on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

# ❌ Fails with django-stubs 5.2.5
qs = Author.objects.prefetch_related(
    Prefetch(
        "books",
        queryset=Book.objects.select_related("author"),
    )
)

Running mypy on this with django-stubs==5.2.5 yields:

error: Argument 1 to "prefetch_related" of "QuerySet" has incompatible type "Prefetch[Literal['books'], _PrefetchedQuerySetT, _ToAttrT]"; expected "str | Prefetch[_LookupT, _PrefetchedQuerySetT, _ToAttrT]"  [arg-type]
error: Argument 1 to "Prefetch" has incompatible type "str"; expected "_LookupT"  [arg-type]
error: Argument "queryset" to "Prefetch" has incompatible type "QuerySet[Book, Book]"; expected "_PrefetchedQuerySetT | None"  [arg-type]

How is that should be

The code should still type-check successfully, since I believe this is valid Django usage, and it worked in previous versions.

I'm not sure exactly what django-money is doing to trigger this here, but unless that pattern is not supposed to be supported, I think it would be good for django-stubs to still support this. Otherwise I'll try to investigate whether django-money's model wrapping with a custom manager needs a rework.

System information

  • OS: MacOS 15.6.1
  • python version: 3.13.2
  • django version: 5.2.6
  • mypy version: 1.18.2
  • django-stubs version: 5.2.5
  • django-stubs-ext version: 5.2.5
  • django-money version: 3.5.4

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