【发布时间】:2021-01-20 22:46:17
【问题描述】:
如何查询模型以获取 ForeignKey“计算”(Autofield?)字段的聚合
我有两个模型:
class Job(models.Model):
name = models.CharField(…)
class LineItem(models.Model):
job = models.ForeignKey(Job, …)
metric_1 = models.DecimalField(…)
metric_2 = models.DecimalField(…)
metric_3 = models.DecimalField(…)
# Making this a @property, @cached_property, or the like makes no difference
def metric_total(self):
return (self.metric_1 + self.metric_2 * self.metric_3)
在视图中:
class StackoverflowView(ListView, …):
model = Job
def get_queryset(self):
return Job.objects
.select_related(…)
.prefetch_related('lineitem_set')
.filter(…).order_by(…)
def get_context_data(self, **kwargs):
context_data = super(StackoverflowView, self).get_context_data(**kwargs)
context_data['qs_aggregate'] = self.get_queryset() \
.annotate(
# Do I need to Annotate the model?
).aggregate(
# This works for any of the fields that have a model field type
metric1Total=Sum('lineitem__metric_1'),
metric2Total=Sum('lineitem__metric_2'),
# This will error :
# Unsupported lookup 'metric_total' for AutoField or join on the field not permitted.
# How do I aggregate the computed model field 'metric_total'?
metricTotal=Sum('lineitem__metric_total'),
)
return context_data
当我尝试聚合计算域时,我收到错误:Unsupported lookup 'metric_total' for AutoField or join on the field not permitted.。如何聚合这些特殊字段?
【问题讨论】:
标签: django django-orm