django-stubs
django-stubs copied to clipboard
Enable django-stubs to recognise members of a Model introduced through related_name argument
class Question(models.Model):
...
class Choice(models.Model):
question_id = models.ForeignKey(Question,on_delete=models.CASCADE,related_name='choice_set')
...
django-stubs isn't able to recognise choice_set as a member of Question model.
reveal_type(question.choice_set.create(choice_text='django'))
Throws error "Question" has no attribute "choice_set"
Would like to take it up, need suggestions on how to proceed.
This is supported, but it seems to break if you use a custom QuerySet this way:
class MyQuerySet(models.QuerySet):
pass
class MyModel(models.Model):
objects = MyQuerySet.as_manager()
You can use the workaround described in README.md:
class MyQuerySet(models.QuerySet):
pass
MyManager = models.Manager.from_queryset(MyQuerySet)
class MyModel(models.Model):
objects = MyManager()
At least this seemed to fix the issue in one of my projects. This seems to be a regression in recent django-stubs releases though, as this previously worked even if the manager wasn't defined in a way that mypy understood.
I'm getting this same warning with 1.10/Django 3.2 where I wasn't when using 1.7/Django 2.2. I don't get the warning if I rollback to 1.9. It's even occurring for models using the default manager.
You might also be affected by https://github.com/typeddjango/django-stubs/pull/902, which is in master but is not released on pypi yet
Thanks for the pointer @ljodal, using master resolves the issues for me.
Closing per MrkGrgsn's comment.