簡體   English   中英

Django-在模板上顯示模型中字段的過濾后總和

[英]Django - Display filtered sum of a field from a model on template

我有一個與(quantidadeEventEvento)有一對多關系的模型(camisaEvento)。 我想在模板上顯示equiidadeEvento中一個字段的總和,但僅顯示camisaEvento上已確定記錄的元素。

在視圖上,我有以下內容,這些內容傳遞到模板的render_to_response:

camisasEvento = camisaEvento.objects.all()
quantidadesEvento = quantidadeEvento.objects.all()

我為camisaEvento的每條記錄制作了一個表,最后我希望它具有一個單元格,該單元格是equiidadeEvento上確定字段的總和,但僅對於for循環上的當前camisaEvento記錄,因此在模板中我有以下內容:

{% for camisa_do_evento in camisasEvento %}
<table>
    <td>...<td>
    <td>...<td>
    .
    .
    .
    <td>The sum should be in here</td>
<table>
{% endfor %}

做這個的最好方式是什么? 我知道這可能很簡單,但是我對編程和Django還是很陌生。

謝謝

您應該在視圖中使用聚合框架來計算總和:

from django.db.models import Sum
camisasEvento = camisaEvento.objects.all().annotate(quantidade_sum=Sum('quantidadeevento__field_to_sum')

其中“ field_to_sum”是要添加的字段。 這將創建稱為屬性quantidade_sum每個camisasEvento包含相關領域的總和。

請注意,在模板中,您可以通過使用反向關系遍歷與每個camisaEvento相關的QuantidadeEvento對象:

<table>
    {% for camisa_do_evento in camisasEvento %}
    <tr>
        {% for quantidade_evento in camisa_do_evento.quantidadeEvento.all %}
          <td>{{ quantidade_evento.my_field }}<td>
        {% endfor }
        <td>Sum: {{ camisa_do_evento.quantidade_sum }}</td>
    </tr>
    {% endfor %}
<table>

為什么不在camisaEvento上使用屬性?

class camisaEvento(models.Model):

    ...

    @property
    def sum_quantity(self):
        # just guessing, don't know exactly what you need
        # it's using python's list comprehension, but you can use a more explicit
        # syntax if you're not familiar with this one
        return sum([obj.field_to_sum for obj in               
                    quantidadeEvento.objects.filter(fk_field=self.id)])

然后,在您的模板中:

{% for camisa_do_evento in camisasEvento %}
    {{ camisa_do_evento.sum_quantity }}
{% endfor %}

工作原理:我在camisaEvento類上創建了一個方法,該方法將camisaEvento該類的所有quantidadeEvento並對其字段進行求和(這是“幻想”邏輯,因為我不完全知道您需要求和什么)。 然后,在模板中,只需調用該方法,就好像它是camisaEvento類的真實屬性一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM