将计算字段拉入模板不与 DISTINCT() 一起使用
我的模型有一个 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
视图.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>
My model has a def on it which returns a calculated field. In my template I'm displaying the fields of my model and my def calculated field displays fine too.
But when I use distinct() in the queryset then the def calculated field no longer appears in the template. Why?
Another question is that the foreign keys are now being displayed as their IDs instead of their unicode.
How can I get the calculated field to display and not have the ids but the usual unicode pull through. Is this possible using 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在视图中,您将
ValuesQuerySet
传递给模板,因此模板中的循环获取字典而不是包含模型实例的常规查询集。我不明白你的第二个问题,但很可能它又与ValuesQuerySet
有关。In the view you are passing a
ValuesQuerySet
to the template, therefore the loop in your template gets dictionaries instead of a regular queryset containing model-instances. I don't understand your second question but most probably it has to do with theValuesQuerySet
again.