Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
himanshu-balasamanta opened this issue Mar 17, 2022 · 5 comments

Comments

@himanshu-balasamanta
Copy link
Contributor

himanshu-balasamanta commented Mar 17, 2022

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.

@ljodal
Copy link
Contributor

ljodal commented Mar 28, 2022

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.

@MrkGrgsn
Copy link
Contributor

MrkGrgsn commented Apr 7, 2022

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.

@ljodal
Copy link
Contributor

ljodal commented Apr 7, 2022

You might also be affected by #902, which is in master but is not released on pypi yet

@MrkGrgsn
Copy link
Contributor

MrkGrgsn commented Apr 8, 2022

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

@intgr
Copy link
Collaborator

intgr commented Nov 8, 2022

Closing per MrkGrgsn's comment.

@intgr intgr closed this as completed Nov 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

4 participants