Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Martin Faucheux Avatar asked Oct 21 '25 08:10

Martin Faucheux


1 Answers

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'))
like image 181
MattRowbum Avatar answered Oct 24 '25 21:10

MattRowbum