Skip to content

"SelfType is unbound" error with custom QuerySet definitions #960

@RJPercival

Description

@RJPercival

Bug report

What's wrong

When defining a custom QuerySet with methods that return the QuerySet, self and the return type should both be a TypeVar so that if the QuerySet is subclassed, the methods defined in the base class return instances of the subclass, e.g.

from django.db import models
from typing import TypeVar

SelfType = TypeVar("SelfType", bound="BaseQuerySet")
ModelType = TypeVar("ModelType", bound="BaseModel")

class BaseQuerySet(models.QuerySet[ModelType]):
   def filter_foo(self: SelfType) -> SelfType:
       return self.filter(foo=True)

class FooQuerySet(BaseQuerySet["FooModel"]):
    pass

FooManager = models.Manager.from_queryset(FooQuerySet)

class BarQuerySet(BaseQuerySet["BarModel"]):
    pass

BarManager = models.Manager.from_queryset(BarQuerySet)

class BaseModel(models.Model):
    class Meta:
        abstract = True
    
    foo = models.BooleanField()

class FooModel(BaseModel):
    objects = FooManager()

class BarModel(BaseModel):
    objects = BarManager()

In standard Python code, this approach works. However, with django-stubs, the following error is printed:

error: Type variable "SelfType" is unbound  [valid-type]
note: (Hint: Use "Generic[SelfType]" or "Protocol[SelfType]" base class to bind "SelfType" inside a class)
note: (Hint: Use "SelfType" in function signature to bind "SelfType" inside a function)

How is that should be

There should not be an error about the type variable being unbound. reveal_type(FooModel.objects.filter_foo()) should print FooQuerySet and reveal_type(BarModel.objects.filter_foo()) should print BarQuerySet.

System information

  • OS:
  • python version: 3.8.3
  • django version: 3.2.13
  • mypy version: 0.950
  • django-stubs version: 1.9.0
  • django-stubs-ext version: 0.3.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions