Django, how to get annotated field of related model

For example, the Invoice model has a project field that points a ForeignKey to the Project model, Project has a custom ProjectManager that has get_queryset defined, in get_queryset I do: super().annotate(display=...)

and when I want to get this annotated field through Invoice: Invoice.objects.filter(project__display__iregex=...) then an error occurs that project does not have a display field, how can I make it so that the related models take fields from some queryset, this is get_queryset() for us

  • Django 4.2.4
  • Python 3.10

To take annotated fields I use Subquery:

Subquery(models.Project.objects.filter(id=OuterRef("project_id")).values_list("display"))

but because of this the request is executed very slowly.

Back to Top