我有几个模型:
class Report(Model):
projects = ManyToManyField('Project', through='ProjectState')
class Project(Model):
cost = IntegerFielf()
class ProjectState(Model):
project = ForeignKey('Project')
report = ForeignKey('Report')
我需要得到一个Report
带有注释字段的列表,该字段avg_cost
是Project.cost
每个report
.
像这样的东西,只有可行的:
Report.objects.filter(...).annotate(
avg_cost=Avg(
Project.objects.values('id', 'cost').filter(
id__in=OutRef('projects__id')
)
)
)
像这样的东西。如果不起作用,在
annotate
插入之前prefetch_related
,指定字段或通过 Prefetch 对象,如果需要额外的复杂过滤