简体   繁体   English

Django:注释相关字段列表

[英]Django: Annotate list of related fields

I have an Company and User models with a related model CompanyRecruiter:我有一个带有相关 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:我想注释作为招聘人员的用户的用户 ID 列表,以便公司以后能够对其进行过滤:

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.我使用postgres。

If you need output similar to the commented section in your example code, you should probably query the CompanyRecruiter model:如果您需要类似于示例代码中注释部分的 output,您可能应该查询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.但是,在评论中,您表示要专门查询Company model。 You should be able to do this with the Postgresql aggregating function ArrayAgg :您应该能够使用 Postgresql 聚合 function ArrayAgg来做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM