Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
How to hint the type of Django's model field `objects` to a dynamically generated class?

I have a Team model in my Django project. I create its custom model manager with QuerySet.as_manager().

class TeamQuerySet(models.QuerySet):
    def active(self) -> "models.QuerySet[Team]":
        return self.filter(is_active=True)

class Team(models.Model):
    is_active = models.BooleanField()

    objects = TeamQuerySet.as_manager()

When I try to execute Team.objects.active(), mypy gives the following error:

error: "Manager[Any]" has no attribute "active"
In [5]: Team.objects
Out[5]: <django.db.models.manager.ManagerFromTeamQuerySet at 0x10eee1f70>

If I was explicitly defining a TeamManager class, there would be not a problem. How can I hint the type of Django model field objects to a dynamically generated class?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Based on the Manager[Any] I assume you are already using django-stubs.

Unfortunately it looks like there's an open issue to make QuerySet.as_manager generic over the model it's attached to that has not been resolved yet.

Even if the PR addressing the issue got merged I'm afraid it wouldn't address your immediate issue because the as_manager needs to be generic over the generic QuerySet subclass used to create the manager in order for both .active to be available and attributes relating to Team be available.

In this regard this other PR, which is unfortunately quite stale, seems to properly address your issue.

over 4 years ago · Santiago Trujillo Denunciar

0

I've worked around this with a little switch-a-roo for MyPy's sake:

_Q = TypeVar("_Q", bound="WorkflowQuerySet")


class WorkflowQuerySet(models.QuerySet["WorkflowModel"]):
    """
    Queryset for workflow objects.
    """

    def count_objects(self) -> int:
        raise NotImplementedError

    def latest_objects(self: _Q) -> _Q:
        raise NotImplementedError


if TYPE_CHECKING:
    # Create a type MyPy understands
    class WorkflowManager(models.Manager["WorkflowModel"]):
        def count_objects(self) -> int:
            ...

        def latest_objects(self) -> _Q:
            ...


else:
    WorkflowManager = WorkflowQuerySet.as_manager


class WorkflowModel(models.Model):
    """
    A model that has workflow.
    """

    objects = WorkflowManager()
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda