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

`through` attribute not defined within model definition

Open mfosterw opened this issue 1 year ago • 0 comments

Bug report

What's wrong

Mypy cannot detect the through attribute of a ManyToManyField within the definition of the enclosing model. To reproduce, add the following test method to MyModel in tests/typecheck/fields/test_related.yml::test_many_to_many:

class MyModel(models.Model):
    auto_through = models.ManyToManyField(Other, related_name="autos")
    # Have multiple M2Ms with implicit through
    other_again = models.ManyToManyField(Other, related_name="others_again")
    custom_through = models.ManyToManyField(Other, through=CustomThrough, related_name="customs")

    objects = MyModelManager()

    def test(self) -> None:
        reveal_type(self.custom_through.through)

Results in:

myapp/models/__init__:31: error: "Other_ManyRelatedManager" has no attribute "through"  [attr-defined]
myapp/models/__init__:31: note: Revealed type is "Any"

How is that should be

Revealed type should be "CustomThrough"

System information

  • OS: macOS 14.2.1
  • python version: 3.12.1
  • django version: 4.2.9
  • mypy version: 1.7.1
  • django-stubs version: 4.2.7
  • django-stubs-ext version: 4.2.7

mfosterw avatar Feb 13 '24 02:02 mfosterw