django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

Enable django-stubs to recognise members of a Model introduced through related_name argument

Open himanshu-balasamanta opened this issue 3 years ago • 4 comments

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.

himanshu-balasamanta avatar Mar 17 '22 11:03 himanshu-balasamanta

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.

ljodal avatar Mar 28 '22 16:03 ljodal

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.

MrkGrgsn avatar Apr 07 '22 03:04 MrkGrgsn

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

ljodal avatar Apr 07 '22 07:04 ljodal

Thanks for the pointer @ljodal, using master resolves the issues for me.

MrkGrgsn avatar Apr 08 '22 01:04 MrkGrgsn

Closing per MrkGrgsn's comment.

intgr avatar Nov 08 '22 13:11 intgr