Skip to content

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

@PureTryOut

Description

@PureTryOut

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingmypy-pluginIssues specific to mypy_django_plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions