Django按月分组并按月显示在模板中

hyrbngr7  于 2023-03-13  发布在  Go
关注(0)|答案(1)|浏览(164)
`class Daily(models.Model):
    transid = models.AutoField(primary_key=True)
    transdate = models.DateField()
    transdetails = models.ForeignKey(Details, on_delete=models.CASCADE)
    transcategory = models.ForeignKey(MasterCategory, on_delete=models.CASCADE)
    transmode = models.ForeignKey(PaymentMode, on_delete=models.CASCADE)
    transsubdetails = models.CharField(max_length=100, blank=False, null=False)
    transamount = models.DecimalField(max_digits=7, decimal_places=2)
    objects = models.Manager()

    def __str__(self):
        return "%s %s %s %s %s %s %s" % (
            self.transid,
            self.transdate,
            self.transdetails,
            self.transcategory,
            self.transmode,
            self.transsubdetails,
            self.transamount)`

以上是我的模型,我的模板如下

{% for month in months %}
<h3>{{ month__month }}</h3>
<table style="width: 100%">
  <tr>
    <th>ID</th>
    <th>Date</th>
    <th>Details</th>
    <th>Category</th>
    <th>Pay Mode</th>
    <th>Sub Details</th>
    <th>Amount</th>
  </tr>
{% for trans in mydata %}
    <tr>
        <td>{{ trans.transid }}</td>
        <td>{{ trans.transdate }}</td>
        <td>{{ trans.transdetails }}</td>
        <td>{{ trans.transcategory }}</td>
        <td>{{ trans.transmode }}</td>
        <td>{{ trans.transsubdetails }}</td>
        <td>{{ trans.transamount }}</td>
    </tr>
{% endfor %}
</table>
{% endfor %}

我的观点是

def alltrans(request):
    my_data = Daily.objects.all()
    mnths = len(Daily.objects.values('transdate__month').distinct())+1
    totamount = Daily.objects.all().aggregate(totb=Sum('transamount'))['totb']
    mnths1 = Daily.objects.values('transdate__month').distinct(),
    monthsba = [Daily.objects.filter(transdate__month=month) for month in range(1, mnths)]
    ms = {
        'months': mnths1,
        'monthsbal': monthsba,
        'mydata': my_data,
        'totamount': totamount,
        'title': 'All Trans',
    }
    return render(request, 'alltrans.html', ms)

我正在尝试按月引入模板...
按月份筛选的一月总和(事务处理金额)= 1 id日期详细信息类别支付模式子详细信息金额
二月总和(交易金额)按月份筛选= 2
等等
请指引我

czfnxgou

czfnxgou1#

您可以在尝试时手动构建数据。通过选择月份(就像您所做的那样),然后在聚合值时循环通过按月份筛选的数据:
views.py

def trans_per_month(request):
    months = Daily.objects.values('transdate__month').distinct()
    data = {}
    for obj in months:
        total = (Daily.objects
                 .filter(transdate__month=obj['transdate__month'])
                 .aggregate(total=Sum('transamount')))
        data[obj['transdate__month']] = total

    context = {'data': data}

    return render(request, 'trans_per_month.html', context)

trans_per_month.html

<table>
    <tr>
        <th>Month</th>
        <th>Total</th>
    </tr>
    {% for month, values in data.items %}
    <tr>
        <td>{{month}}</td>
        <td>{{values.total}}</td>
    </tr>
    {% endfor %}
</table>

相关问题