4

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.

1 Answer 1

5

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

I need to apply the annotation on a Company queryset. Querying the CompanyRecruiter table would make me do 2 DB calls and I would like to keep all in one to be efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.