Skip to content

Commit

Permalink
Fix incorrect queryset generic types
Browse files Browse the repository at this point in the history
  • Loading branch information
craigds committed Jan 22, 2025
1 parent 0e8ea6e commit 16d68cc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
7 changes: 7 additions & 0 deletions testapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,10 @@ class Developer(Employee):
class Manager(Employee):
# Adds the _exact_ same field as Developer. Shouldn't error.
name = models.CharField(max_length=255, null=True)


def typed_queryset() -> None:
# This isn't actually called, but it's here for the mypy check to ensure that type hinting works correctly.
queryset = Animal.objects.filter(pk=1)
reveal_type(queryset) # QuerySet[Animal]
queryset.filter(name="lynx") # works, because Animal has this field
13 changes: 8 additions & 5 deletions typedmodels/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from functools import partial
import types
import typing
from typing import ClassVar, cast
from typing import ClassVar, cast, Generic, TypeVar
from typing_extensions import Self

import django
from django.core.exceptions import FieldDoesNotExist, FieldError
Expand All @@ -20,13 +21,15 @@

reveal_type = print

T = TypeVar("T", bound="TypedModel")

class TypedModelManager(models.Manager["TypedModel"]):
def get_queryset(self) -> QuerySet:

class TypedModelManager(models.Manager[T]):
def get_queryset(self) -> QuerySet[T]:
qs = super(TypedModelManager, self).get_queryset()
return self._filter_by_type(qs)

def _filter_by_type(self, qs: QuerySet) -> QuerySet:
def _filter_by_type(self, qs: QuerySet[T]) -> QuerySet[T]:
if hasattr(self.model, "_typedmodels_type"):
if len(self.model._typedmodels_subtypes) > 1:
qs = qs.filter(type__in=self.model._typedmodels_subtypes)
Expand Down Expand Up @@ -400,7 +403,7 @@ def say_something(self):
_typedmodels_registry: ClassVar[dict[str, type["TypedModel"]]]
_meta: ClassVar[TypedModelOptions]

objects = TypedModelManager()
objects: ClassVar[TypedModelManager[Self]] = TypedModelManager()

type = models.CharField(
choices=(), max_length=255, null=False, blank=False, db_index=True
Expand Down

0 comments on commit 16d68cc

Please sign in to comment.