New problem when typing custom `Model.objects` in version 1.13.1
Bug report
What's wrong
After updating to version 1.13.1 I've add a new typing problem appear in my models file. Here is a simplistic version. This file contains two models A and B that can point to each other.
from typing import TypeVar
from django.db import models
T = TypeVar("T", bound=models.Model)
class MyQuerySet(models.QuerySet[T]):
pass
class MyModelA(models.Model):
objects = MyQuerySet.as_manager()
modelB = models.ForeignKey("MyModelB", on_delete=models.CASCADE)
class MyModelB(models.Model):
modelA = models.ForeignKey(MyModelA, null=True, blank=True, on_delete=models.SET_NULL)
With version 1.13.0 this passes fine, but with 1.13.1 mypy raises an error:
error: Need type annotation for "objects" [var-annotated]
This initial problem can be solved by adding a type annotation:
class MyModelA(models.Model):
objects: "models.Manager[MyModelA]" = MyQuerySet.as_manager()
However that wasn't necessary in the previous version. Moreover this new annotation leads mypy to raise a new error :
error: Couldn't resolve related manager for relation 'mymodela' (from myapp.models.MyModelA.myapp.MyModelA.modelB). [django-manager-missing]
This new error is present in both versions 1.13.1 and 1.13.0. I don't know how to fix that one.
How is that should be
I'd expect the annotation to be unneeded as it wasn't in the previous version and it seems clear enough.
With the annotation I would also expect no error here, as my models should be well-typed, and the code runs fine.
System information
- OS: Kubuntu 22.10
-
pythonversion: 3.10.7 -
djangoversion: 4.1.4 -
mypyversion: 0.991 -
django-stubsversion: 1.13.1 (worked on 1.13.0) -
django-stubs-extversion: 0.7.0
@clouds56 I'm guessing the Need type annotation for "object" error may be caused by #1150?
Any thoughts how to fix it?
Similar problem here. I am using VSCode extension Pylance which bundles django-stubs inside, the definition of Model instance's objects can not be found after updating:
from django.db.models import Model
Model.objects # "Go To Definition" works in VSCode
def func(model: Model):
model.objects # "Go To Definition" says "No definition found"
Didn't find a way to specify version of django-stubs inside Pylance's extension configs, finally choose to clone this repo and use symbolic link instead. Anyway, changing back to version 1.13.0 solves the problem, and the reason seems to be the movement of #1150 , maybe instance's property from metaclass can not be correctly parsed while class's property from metaclass can.
Pylance actually does not ship with django-stubs
https://github.com/microsoft/pylance-release/issues/4562#issuecomment-1615049922
@tkoft Thanks for the information, I see the problem is fixed in https://github.com/sbdchd/django-types/pull/181
I'm closing this as I cannot reproduce with the provided code. Feel free to post a new issue or provide any new repro case here and I'll reopen.