djangodjango-aggregationdjango-annotatedjango-subquery

Django: Annotate list of related fields


I have an Company and User models with a related model CompanyRecruiter:

class CompanyRecruiter(models.Model):

    organization = models.ForeignKey(Company, related_name="company_recruiters")
    recruiter = models.ForeignKey(User, related_name="company_recruiters")

I want to annotate the list of user ids of users who are recruiters for companies to be able to filter on them later:

Company.objects.annotate(some_stuff=some_other_stuff).values_list("user_ids", flat=True)
# [ [1, 2], [1, 56], [] ]

I already tried with Custom Aggregates and Subqueries without success. I use postgres.


Solution

  • If you need output similar to the commented section in your example code, you should probably query the CompanyRecruiter model:

    recruiters = CompanyRecruiter.objects.values_list('organization', 'recruiter')
    recruiter_list = [[o, r] for o, r in recruiters]
    

    However, in the comments you have indicated that you want to specifically query the Company model. You should be able to do this with the Postgresql aggregating function ArrayAgg:

    Company.objects.annotate(recruiter_ids=ArrayAgg('company_recruiters__recruiter'))