首页 文章

将计算字段拉入不与DISTINCT()一起使用的模板

提问于
浏览
1

我的模型有一个def,它返回一个计算字段 . 在我的模板中,我显示模型的字段,我的def计算字段也显示正常 .

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

另一个问题是外键现在显示为ID而不是unicode .

我如何才能显示计算字段而不是id,而是通常的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)

contract.html

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

1 回答

  • 1

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

相关问题