【问题标题】:How do you query a model for an aggregate of a ForeignKey computed field如何查询模型以获取 ForeignKey 计算字段的聚合
【发布时间】: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


    【解决方案1】:

    你也必须计算metric_total

    Job.objects.aggregate(
        metric1Total=Sum('lineitem__metric_1'),
        metric2Total=Sum('lineitem__metric_2'),
        metric_total=Sum('lineitem__metric_1') + Sum('lineitem__metric_2')
    )

    可能的重复:Django @property used in .aggregate()

    简而言之,这些annotate()aggregate() 方法在数据库级别执行,而metric_total()“方法” 在 Python 级别执行。

    【讨论】:

    • 无论如何将模型文件中的方法“链接”到 SQL 查询以/确保/数学/计算保持不变?
    • 如果我们使用“正确的数学运算符”,结果将保持不变
    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 2022-11-30
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2023-01-03
    相关资源
    最近更新 更多