[英]How to sort based on a choice field in django in template
考慮以下模型:
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
我想對對象進行排序,以便可以將左邊的對象與右邊的對象分開,並在html文檔的不同部分中顯示它們。 就像是:
{% 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 %}
我知道這行不通。 但是我只是想對我想要的東西給出一個想法。 對於Django模型中的任何其他字段類型,該過程也將類似嗎?
您可以嘗試這樣的事情:
{% 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.