Skip to content

When a function returns a queryset that is only annotated for a filter #3382

@delfick

Description

@delfick

I originally made this as a discussion but I get this feeling you don't get notifications for those. My apologies for the spam!

So in making my QuerySets defined as generic so that django-stubs starts to understand .annotate properly I have a problem where I don't want to always recognise that a queryset is annotated.

For example

def make_my_filtered_queryset(qs: MyQuerySet) -> MyQuerySet:
    return qs.annotate(some_count=Count(....)).filter(some_count==1)

After I make my queryset generic it starts to complain at me along the lines of

Incompatible return value type (got "MyQuerySet[MyModel@AnnotatedWith[TypedDict({'some_count': Any})], MyModel@AnnotatedWith[TypedDict({'some_count': Any})]]", expected "MyQuerySet[MyModel]")  [return-value]

I'd rather not add several hundred TypedDicts for annotations that aren't relevant out of the immediate .filter that uses them.

I'm wondering what y'all think about this situation and whether it's reasonable for mypy to say an annotated queryset is a superset of it's unannotated equivalent?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions