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

.annotate(...) does not seem to work with reverse-related foreign key lookupu #2382

Open
asottile-sentry opened this issue Sep 24, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@asottile-sentry
Copy link

Bug report

wrote a little testcase -- will see if I can figure out a quick fix for it

- case: test_annotate_reverse_related
  main: |
    from myapp.models import MB
    from django.db.models import Count

    o = MB.objects.annotate(Count("mas")).get()
    reveal_type(o.mas__count)  # N: Revealed type is "builtins.int"
  installed_apps:
    - myapp
  files:
    - path: myapp/__init__.py
    - path: myapp/models.py
      content: |
        from django.db import models

        class MA(models.Model):
            mb = models.ForeignKey("MB", related_name="mas", on_delete=models.CASCADE)

        class MB(models.Model): pass

What's wrong

_______________________________________ test_annotate_reverse_related _______________________________________
/Users/asottile/workspace/sentry-forked-django-stubs/tests/typecheck/managers/querysets/test_annotate.yml:405: 
E   pytest_mypy_plugins.utils.TypecheckAssertionError: Invalid output: 
E   Actual:
E     main:5: error: "MB" has no attribute "mas__count"  [attr-defined] (diff)
E     main:5: note: Revealed type is "Any"          (diff)
E   Expected:
E     main:5: note: Revealed type is "builtins.int" (diff)
E   Alignment of first line difference:
E     E: main:5: note: Revealed type is "builtins.int"
E     A: main:5: error: "MB" has no attribute "mas__count"  [attr-defined]
E                ^

How is that should be

should resolve correctly

System information

  • OS:
  • python version: 3.12.6
  • django version: 5.1.1
  • mypy version: 1.11.
  • django-stubs version: 5.1.0
  • django-stubs-ext version: 5.1.0
@asottile-sentry asottile-sentry added the bug Something isn't working label Sep 24, 2024
@asottile-sentry
Copy link
Author

ah I see from reading the code that it just doesn't support non-named arguments. there's a few tests which are passing just due to luck it seems (since they also use non-named arguments assuming they'll produce a WithAnnotations)

what's a little weird is this seems to have worked before django-stubs 5.1.0 -- but I suspect that was due to the old implementation being buggy

@asottile-sentry
Copy link
Author

actually just one test:

qs = User.objects.annotate(Count('id'))

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

No branches or pull requests

1 participant