typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.51k stars 425 forks source link

`RawQuerySet` has conflicting errors: "is not subscriptable" vs "Missing type parameter" #2236

Open hterik opened 1 week ago

hterik commented 1 week ago

Bug report

What's wrong

Using RawQuerySet as type annotation is not possible. Without the generic parameter, mypy fails with is not subscriptable error. With the generic parameter, python throws TypeError.

from django.db.models.query import RawQuerySet
from models import MyModel

# TypeError: type 'RawQuerySet' is not subscriptable
def foo() -> RawQuerySet[MyModel]:                  
    return MyModel.objects.raw("SELECT id FROM my_model")

# mypy error: Missing type parameters for generic type "RawQuerySet"  [type-arg]
def bar() -> RawQuerySet:                           
    return MyModel.objects.raw("SELECT id FROM my_model")

System information

flaeppe commented 1 week ago

Looks like RawQuerySet is missing from the monkeypatch list of classes to add __class_getitem__ to:

https://github.com/typeddjango/django-stubs/blob/590f033abb9f0b3d10360a975c17b851a8222b88/ext/django_stubs_ext/patch.py#L55-L81

A PR is welcome for fixing that

intgr commented 1 week ago

As a work-around, you can also use quoted type hints, e.g.

def foo() -> "RawQuerySet[MyModel]":                  
    return MyModel.objects.raw("SELECT id FROM my_model")

or alternatively, add from __future__ import annotations to the beginning of the file, which causes evaluation of all type hints to be deferred.