简体   繁体   English

如何根据模板中django中的选择字段进行排序

[英]How to sort based on a choice field in django in template

Consider the following model: 考虑以下模型:

class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    POSITIONS = (
            ('L', 'Left'),
            ('R', 'Right')
        )
    position = models.CharField(max_length=1, choices=POSITIONS, default='R')
    class Meta:
        verbose_name_plural = 'categories'
    def __str__(self):
        return self.name

I want to sort the objects in a manner such that I can separate the left ones from the right ones and show them in separate parts of the html document. 我想对对象进行排序,以便可以将左边的对象与右边的对象分开,并在html文档的不同部分中显示它们。 Something like: 就像是:

{% for category in categories|sort_by: "position" = "left" %}
        <ul class="collection with-header">
         <li class="collection-header">
          <h3>{{category.name}}</h3>
             <p><small>{{category.description}}</small></p>
         </li>
            {% for url in category.extra_link_set.all %}
            <li class="collection-item"><a href="{{url.url}}">{{url.url_text}}</a></li>
            {% endfor %}

        </ul>
        {% endfor %}

I know this wont work. 我知道这行不通。 But I am just trying to give an idea as to what I want. 但是我只是想对我想要的东西给出一个想法。 Also would the process be similar for any other field type in django models? 对于Django模型中的任何其他字段类型,该过程也将类似吗?

You could try something like this: 您可以尝试这样的事情:

{% for category in categories %}
    <div class="left_stuff">
        {% if category.position=='L' %}
            <h3>...</h3>
            .....
        {% endif %}
    </div>
{% endfor %}

{% for category in categories %}
    <div class="right_stuff">
        {% if category.position=='R' %}
            <h3>...</h3>
            .....
        {% endif %}
    </div>
{% endfor %}

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

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