I am using Pyright to type-check a Django app, and I have been struggling for quite some time with how to add a type hint for a QuerySet after an annotate
query.
Let’s take this annotate from the official documentation:
q = Blog.objects.annotate(number_of_entries=Count("entry"))
Every item in the result now has an attribute number_of_entries
. How can I create a type hint for that easily (a class that has all the model attributes and the additional annotated attribute)?
There is a WithAnnotations
helper in django-stubs
, but this is something not standard and not supported by Pyright.
Python also strangely doesn’t support type hint intersections (the issue is from 2014 ) and unions don’t help here.
Using Protocol
would need me to completely retype all attributes from the original Model itself and additionally the extra attributes, which doesn’t make sense to me.
For now, I just ignore the type hints on those extra attributes, but is there really no nice solution for that?