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 not typed properly when using import alias for related model #2128

Closed
tkoft opened this issue May 6, 2024 · 2 comments · Fixed by #2153
Closed

ManyToManyField not typed properly when using import alias for related model #2128

tkoft opened this issue May 6, 2024 · 2 comments · Fixed by #2153
Labels
bug Something isn't working mypy-plugin Issues specific to mypy_django_plugin

Comments

@tkoft
Copy link

tkoft commented May 6, 2024

Bug report

What's wrong

Looks like the transformer for ManyToManyField doesn't handle the case for when the related model passed in is aliased. The to model is still typed properly, since it's inferred and returned as the FunctionContext default_return_type, but any generated through model is never typed.

Example:

from django.contrib.auth import models as auth_models
from django.db import models

class MyModel(models.Model):
    allowed_groups = models.ManyToManyField(auth_models.Group)

I believe get_model_from_expression() gets passed a MemberExpr as such:

MemberExpr:11(
  NameExpr(auth_models [django.contrib.auth.models])
  Group [django.contrib.auth.models.Group])

But this case is only handled explicitly for the django.contrib.auth.models.User model. In other cases, it returns None, and the transform for the whole field just returns the default value.

How is that should be

Since normal RelatedFields resolve their related models fine with aliased imports, it seems the manytomany transformer should be able to use the same logic (a la django_context.get_field_related_model_cls(current_field)) for resolving both its to and through models. Though I'm sure there's some complexities around how Django models m2m relations that would require some changes from how get_field_related_model_cls works.

System information

  • OS:
  • python version: 3.8
  • django version: 4.2.9
  • mypy version: 1.10
  • django-stubs version: 5.0
  • django-stubs-ext version:
@tkoft tkoft added the bug Something isn't working label May 6, 2024
@tkoft
Copy link
Author

tkoft commented May 6, 2024

Actually, I think the easiest fix is to change this condition to check for RefExpr instead of NameExpr:

if isinstance(expr, NameExpr) and isinstance(expr.node, TypeInfo):

@flaeppe
Copy link
Member

flaeppe commented May 12, 2024

Thanks for the clear report and a fix, I've opened #2153 with your suggestion

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.

2 participants