Skip to content

Allow lookups on .annotate fields #2376

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Conversation

sterliakov
Copy link
Contributor

Allow lookups on fields coming from .annotate()

Django does not object when fields introduced via QuerySet.annotate are used in .filter with lookup chains:

from django.db import models

class Blog(models.Model): pass

Blog.objects.annotate(id2=models.F('id')).filter(id2__gt=10)

mypy, however, rejects this with a really cryptic error message:

error: Cannot resolve keyword 'id2' into field. Choices are: id, id2  [misc]

Since now all .annotate fields are resolved as plain Any, I think it's fair to allow chaining any lookups with them. This PR does exactly that: when a id2__something lookup is encountered and id2 is not a model field, proceed with checking that id2 is .annotate field and accept if so, ignoring the chained lookups.

Copy link
Member

@flaeppe flaeppe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, just one fix with the tests

@sterliakov
Copy link
Contributor Author

Tangentially related to #2306 and #2302? This should get rid of lookup problem there, but still doesn't support alias.

I'll grab .alias() as well, it also causes problems in my codebase:)

@flaeppe
Copy link
Member

flaeppe commented Sep 20, 2024

I think we need a third type argument on QuerySet to resolve alias?

Or at least that might be one alternative way

@flaeppe flaeppe merged commit eb6535f into typeddjango:master Sep 20, 2024
36 checks passed
@flaeppe flaeppe mentioned this pull request Sep 23, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants