Skip to content
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

ManyToManyField is typed as RelatedManager[<model>] | None rather than just RelatedManager[<model>] #1638

Closed
PureTryOut opened this issue Aug 2, 2023 · 2 comments · Fixed by #1720
Labels
bug Something isn't working mypy-plugin Issues specific to mypy_django_plugin

Comments

@PureTryOut
Copy link

What's wrong

I have the following model:

class Customer(User):
    addresses = models.ManyToManyField(
        Address,
        related_name="customers",
        null=True,
        blank=True,
    )

addresses here is typed as RelatedManager[<model>] | None. meaning any queryset call on it will make mypy complain about the attribute not existing. For example:

project/views/address.py:68: error: Item "None" of "RelatedManager[Address] | None" has no attribute "add"  [union-attr]
project/views/address.py:93: error: Item "None" of "RelatedManager[Address] | None" has no attribute "get"  [union-attr]
project/views/address.py:97: error: Item "None" of "RelatedManager[Address] | None" has no attribute "remove"  [union-attr]

However, it never is None, and I'm not sure how it could be either. If there are no addresses for a customer than customer.addresses.exists() would just return false rather than customer.addresses being None.

How is that should be

It should be typed as just RelatedManager[<model>].

System information

  • OS: Linux
  • python version: 3.11
  • django version: 4.2
  • mypy version: 1.4.1
  • django-stubs version: 4.2.3
  • django-stubs-ext version: not installed
@PureTryOut PureTryOut added the bug Something isn't working label Aug 2, 2023
@sobolevn
Copy link
Member

sobolevn commented Aug 2, 2023

Does null=True or blank=True affect | None part?

@andersk
Copy link
Contributor

andersk commented Aug 10, 2023

The ManyToManyField documentation says

null has no effect since there is no way to require a relationship at the database level.

and in fact the system check framework raises the fields.W340 warning for this. django-stubs should ignore null here too, but meanwhile you can just remove it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working mypy-plugin Issues specific to mypy_django_plugin
Development

Successfully merging a pull request may close this issue.

4 participants