代码之家  ›  专栏  ›  技术社区  ›  geejay

在django模板中按类别列出产品

  •  4
  • geejay  · 技术社区  · 15 年前

    在django模板中,生成每个类别都有标题的HTML和该类别下的产品的最佳方法是什么?

    我玩弄着要一本传字典或一份有顺序的清单的想法…

    3 回复  |  直到 15 年前
        1
  •  8
  •   Wade    15 年前

    查看重新组合模板筛选器

    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
  •  4
  •   utku_karatas    15 年前

    除了@wade建议的以外,您还可以在类别模型中添加一个方法来返回它拥有的产品。

    例子。。

    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
  •  1
  •   geejay    15 年前

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

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

    然后使用过滤器标签

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