【问题标题】:pulling calculated field into template not working with DISTINCT()将计算字段拉入模板不适用于 DISTINCT()
【发布时间】:2011-06-16 21:11:47
【问题描述】:

我的模型上有一个定义,它返回一个计算字段。在我的模板中,我正在显示我的模型的字段,并且我的 def 计算字段也显示得很好。

但是当我在查询集中使用 distinct() 时,def 计算字段不再出现在模板中。为什么?

另一个问题是外键现在显示为它们的 ID 而不是它们的 unicode。

我怎样才能让计算的字段显示而不是 ids 但通常的 unicode 拉出。这可以使用 distinct() 吗?

models.py

@property
def calculated_total(self):
    aggregated_cost = sum([m.total for m in Fee.objects.filter(contract=self.contract,grouping=self.grouping,\
                        party_incurring_fee=self.party_incurring_fee,\
                        party_paying_fee=self.party_paying_fee)])
    return aggregated_cost

views.py

calculated_subtotal_queryset = Fee.objects.values('party_incurring_fee', 'party_paying_fee', 'grouping').distinct()

context_dict = {
    'Subtotal' : calculated_subtotal_queryset,
}
return render_to_response('contract.html', context_dict)

合同.html

                {% for s in Subtotal %}
                <tr>
                    <td>{{ s.calculated_total }}</td>

【问题讨论】:

    标签: django distinct django-queryset


    【解决方案1】:

    在视图中,您将 ValuesQuerySet 传递给模板,因此模板中的循环获取字典而不是包含模型实例的常规查询集。我不明白你的第二个问题,但很可能又与ValuesQuerySet 有关。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 2012-09-04
      相关资源
      最近更新 更多