【问题标题】:List products by category in Django template在 Django 模板中按类别列出产品
【发布时间】:2010-11-21 15:42:34
【问题描述】:

在 Django 模板中生成具有每个类别标题的 HTML 以及该类别下的产品的最佳方法是什么?

我玩弄了一个传递字典或有序列表的想法......

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    看看重组模板过滤器

    http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

    有了它,你可以做这样的事情:

    {% regroup products by category as products_by_category %}
    {% for c in products_by_category %}
      <h1>{{c.grouper}}</h1>
      <ul>
        {% for p in c.list %}
          <li>{{p.name}}</li>
        {% endfor %}
      </ul>
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      除了@Wade 的建议之外,您还可以向您的 Category 模型添加一个方法来返回它拥有的产品。

      例子..

      class Category:
      ... 
      ...  
          def get_products(self):
              return Product.objects.filter(category=self)
      

      然后在模板中你可以..

      {% for category in categories %} # assuming categories is passed from the view.
          {% for product in category.get_products %}
      ...
      

      【讨论】:

        【解决方案3】:

        在视图代码中使用了排序列表,

        sorted(dom_obj.objects.all(), key=lambda d: d.sort_key)
        

        然后使用过滤标签

        {% ifchanged %}<h1>{{ prod.cat }}</h1>{% endifchanged %}
        

        【讨论】:

          猜你喜欢
          • 2019-04-01
          • 1970-01-01
          • 2015-04-09
          • 1970-01-01
          • 2020-11-12
          • 2018-10-01
          • 2018-07-08
          • 2013-09-29
          • 2021-05-23
          相关资源
          最近更新 更多