Django HTML通过动态字典名进行迭代

2024-06-02 12:10:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个网站,在这个网站中,我使用html中的动态选项卡,每个选项卡将显示不同的数据

现在我要做的是,在views.py中,我为不同的选项卡创建不同的词典。到目前为止,我已经在views.py文件中创建了以下内容

def display_rpt (request):
    alltrasfData={}
    sec = Section.objects.all()
    for key in sec:
        transactions = Transaction.objects.values('feast_year__title','feast_year','feast_group__title','section','section__short').filter(section_id=key.id).order_by('section','-feast_year','-feast_group__title').annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))
        subtotal = Transaction.objects.values('section','feast_year','feast_year__title').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))
        grandtotal = Transaction.objects.values('section').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))
        alltrasfData[f'transactions_{key.id}']=transactions
        alltrasfData[f'subtotal_{key.id}']=subtotal
        alltrasfData[f'grandtotal_{key.id}'] = grandtotal
    alltrasfData['sec']=sec
    return render(request, 'homepage/reports.html',alltrasfData)

为了让您了解AllTransfData中的一些词典:

“交易记录1”、“交易记录2”、“交易记录3”

在Django html中是否有一种方法可以使用动态字典名通过这些不同的字典进行迭代


Tags: keyidobjectstitlehtmlsectionsecyear
2条回答

您可以使用^{}模板标记非常轻松地在模板中的dict上迭代

{% for key, values in alltrasfData.items %}
    {% if 'transaction' in key %}
        {% for transaction in values %}
            <p>feast_year: {{transaction.feast_year}}</p>
            <p>...</p>
        {% endfor %}
    {% elif 'subtotal' in key %}
        # logic for subtotal goes here
        # ...
    {% else %}
         # logic for grandtotal goes here
        # ...
    {% endif %}
{% endfor %}

我认为将alltrasfData存储在字典context中,将其传递给render(),并在HTML中使用以下内容:

{% for key,value in alltrasfData %}
    print(key,value)
{% endfor %}

相关问题 更多 >