Paulo-99
Paulo-99

Reputation: 35

Is there a solution to type hint a django annotation?

I have a django project which I am trying to type and add type checking through mypy. I want to use django annotations to get more informations about an object. This operation adds properties to a class already declared. The package django-stubs already provides a typing class WithAnnotations that should do the work but it doesn't.

To be clear, I simply want this code to pass mypy

from django.db import models

class User(models.Model):
  first_name: models.CharField()
  last_name: models.CharField()

class Team(models.Model):
  users: models.ManyToManyField(User)

class House(models.Model):
  inhabitants: models.ManyToManyField(User)

users = User.objects.all()
for user in users:
  print(user.first_name)

users_with_teams = Users.objects.all().annotate(teams_ids=ArrayAgg(...))
users_with_teams_and_houses = users_with_teams.annotate(houses_ids=ArrayAgg(...))

for user in users_with_teams:
  print(user.first_name)
  print(user.teams_ids)
  print(user.houses_ids)
  

If I try to run it I get errors object User has no attribute teams_ids or object User has no attribute houses_ids

I thought it would be nice to have it in functions:

from typing import TypeVar

T = TypeVar("T")

def annotate_teams(query: QuerySet[T]) -> QuerySet[SomethingElseButWhat]:
  return query.annotate(teams_ids=ArrayAgg(...))

but I don't know which type my function should return.

Does any of you know if what I am looking for is possible ?

Upvotes: 0

Views: 43

Answers (0)

Related Questions