【问题标题】:Django grouping results by filedDjango按字段分组结果
【发布时间】:2012-09-27 14:36:15
【问题描述】:

对不起菜鸟问题。 假设我们有一个具有关系的模型:

  class Book(models.Model):
     name = models.CharField(max_length=300)
     category = models.ForeignKey(Category)

  class Category(models.Model):
     name = models.CharField(max_length=300)

是否有可能以某种方式对结果进行分组,以便在模板中我们可以有这样的东西?

<ul>
   {% for category in book_categories%}
              <li> 
                  {{category.name}} 
                   <br/>  
                  {% for book in category%}
                      {{book.name}} , {{book.author}}, etc...
                  {% endfor %} 
             </li>
   {% endfor %}           
</ul>

还是我把事情弄复杂了,有一种更简单的方法可以实现这样的 html 输出?

【问题讨论】:

    标签: python django django-models django-templates iteration


    【解决方案1】:

    将类别传递给您的模板,然后您可以执行类似的操作

    <ul>
       {% for category in categories %}
                  <li> 
                      {{category.name}} 
                       <br/>  
                      {% for book in category.book_set.all %}
                          {{book.name}} , {{book.author}}, etc...
                      {% endfor %} 
                 </li>
       {% endfor %}           
    </ul>
    

    【讨论】:

    • 就是这样!我知道有这么简单的东西)非常感谢!
    【解决方案2】:

    您可以只加载按类别排序的书籍,然后在模板中添加如下内容:

    <ul>
      {% for book in books %}
        <li>
            {% ifchanged book.category__name %}
                {{ book.category__name }}
            {% endifchanged %}
    
            <br/>  
            {{book.name}} , {{book.author}}, etc...
        </li>
      {% endfor %}          
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-21
      • 2016-09-07
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      相关资源
      最近更新 更多