Mutual M2M models cause RelatedManager lookup failures in 6.0.8
bug
# Bug report
<!--
Hi, thanks for submitting a bug. We appreciate that.
But, we will need some information about what's wrong to help you.
-->
## What's wrong
`models.py` in a test project:
```python
from typing import Self
from django.db import models
class Collection(models.Model):
name = models.CharField()
child_collections = models.ManyToManyField(
"self",
through="ds.CollectionItem",
through_fields=("parent_collection", "collection"),
related_name="parent_collections",
symmetrical=False,
)
class CollectionItemQuerySet[A](models.QuerySet["CollectionItem", A]):
def active(self) -> Self:
return super().filter(removed_at__isnull=True)
class CollectionItemManager(models.Manager["CollectionItem"]): ...
class CollectionItem(models.Model):
parent_collection = models.ForeignKey(
Collection, on_delete=models.PROTECT, related_name="child_items"
)
collection = models.ForeignKey(
Collection, on_delete=models.CASCADE, related_name="collection_items", null=True
)
removed_at = models.DateTimeField(blank=True, null=True)
objects = CollectionItemManager.from_queryset(CollectionItemQuerySet)()
def __main__() -> None:
Collection.objects.get().child_items.active()
if __name__ == "__main__":
__main__()
```
```console
$ uv run -p 3.14 -w 'django-stubs==6.0.8,mypy' mypy src
src/ds/models.py:37: error: "RelatedManager[CollectionItem]" has no attribute "active" [attr-defined]
Found 1 error in 1 file (checked 8 source files)
```
I've heavily reduced this from a [real project](https://salsa.debian.org/freexian-team/debusine) where we started seeing CI failures after django-stubs 6.0.8 was released earlier today.
Getting rid of the `Collection.child_collections` M2M field works around the problem. I may do this anyway since even in our actual project this field only turns out to be of quite marginal utility, but nevertheless this seems to be a bug. I think the transformer fails to resolve `CollectionItem`'s default manager due to the mutual references.
## How is that should be
```console
$ uv run -p 3.14 -w 'django-stubs==6.0.7,mypy' mypy src
Success: no issues found in 8 source files
```
## System information
- OS:
- `python` version: 3.14.6
- `django` version: 5.2
- `mypy` version: 2.3.0
- `django-stubs` version: 6.0.8
- `django-stubs-ext` version: 6.0.8
2 条评论