按所属类别列出项目

2024-06-03 08:58:10 发布

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

我是个十足的新手,所以请容忍我。我以前从未使用过OOP或框架

我正在创建一个簿记系统,希望分类账按其所属的类别显示。这是我的模型,它似乎起作用了:

class COAGroup(models.Model):
    Name = models.CharField(max_length=200)
    def __str__(self):
        return self.Name

class Ledger(models.Model):
    Name = models.CharField(max_length=200)
    COAGroup = models.ForeignKey(COAGroup, on_delete=models.CASCADE)
    def __str__(self):
        return self.Name

我正在研究我的第一个视图,它应该按分类列出所有分类账。例如

<h2>Some COAGroup Name</h2>
<ul>
 <li>A ledger that belongs to this group</li>
 <li>Another ledger that belonds to the group</li>
 <li>And another</li>
</ul>

<h2>Another COAGroup</h2>
<ul>
 <li>A ledger that belongs to this second group</li>
 <li>Another ledger</li>
</ul>

我在views.py中编写了以下视图:

def showledgers(request):  
    COAGroups = COAGroup.objects.all()
    Ledgers = Ledger.objects.all()
    context = {
        "COAGroups":COAGroups,
        "Ledgers":Ledgers,
    }
    return render(request,"ListLedgers.html",context)

我已经设法让账本显示在ListLedgers.html中,但是我不知道如何按照我的示例让它们按COA组列出

谢谢你


Tags: tonameselfreturnthatmodelsdefgroup
1条回答
网友
1楼 · 发布于 2024-06-03 08:58:10

在您看来,您最好已经^{} [Django-doc]相关的Ledger

def showledgers(request):  
    COAGroups = COAGroup.objects.prefetch_related('ledger')
    context = {
        'groups': COAGroups,
    }
    return render(request, 'ListLedgers.html', context)

然后在模板中,您可以遍历COAGroups,对于每个这样的组,遍历相关的.ledger_set

{% for group in groups %}
  <h2>{{ group.Name }}</h2>
  <ul>
  {% for ledger in group.ledger_set.all %}
    <li>{{ ledger.name }}</li>
  {% endfor %}
</ul>
{% endfor %}

Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: name instead of Name.

相关问题 更多 >