简体   繁体   English

按项目所属的类别列出项目

[英]Listing items by the category they belong to

I'm a complete Newb so please bear with me.我是一个完整的新手,所以请多多包涵。 I've never used OOP or a framework before.我以前从未使用过 OOP 或框架。

I'm creating a book keeping system where I want the ledgers to be displayed by the category they belong to.我正在创建一个簿记系统,我希望分类帐按它们所属的类别显示。 Here's my model and it seems to work:这是我的模型,它似乎有效:

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

I'm working on my first view which should list all the ledgers by the category they belong to.我正在处理我的第一个视图,它应该按它们所属的类别列出所有分类帐。 Eg例如

<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>

I've written the following view in views.py:我在 views.py 中编写了以下视图:

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

I've managed to get the ledgers to show in ListLedgers.html but I can't figure out how to get them to list by COA Group as per my example.我已经设法让分类帐显示在 ListLedgers.html 中,但我不知道如何按照我的示例让它们由 COA Group 列出。

Thank you!谢谢!

In your view, you better already .prefetch_related(..) [Django-doc] the related Ledger s:在您看来,您最好已经.prefetch_related(..) [Django-doc]相关的Ledger s:

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

Then in the template, you can iterate over the COAGroups , and for each such group over the related .ledger_set :然后在模板中,您可以迭代COAGroups ,并在相关的.ledger_set为每个这样的组.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 .注意:通常 Django 模型中字段的名称是用snake_case写的,而不是PerlCase ,所以它应该是: name而不是Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM