本文介绍了Django分组查询由第一个字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个QuerySet,如:
I have a QuerySet like:
items = Item.objects.all()
项目有一个名称字段。在我想显示的模板中:
Item has a 'name' field. In the template I want to show:
- A
- 轴
- 酒精
- B
- Bazookas
- C
- 硬币
- 墨盒
- S
- Swords
- 麻雀
- A
- Axes
- Alcohol
- B
- Bazookas
- C
- Coins
- Cartridges
- S
- Swords
- Sparrows
所以这些项目是按照第一个字母排序和分组的。遗漏的字母被省略。有没有人有任何想法?
So the items are ordered and group by the first letter. Missing letters are omitted. Does anyone have any ideas?
推荐答案
有一个模板标签,如果你关心的是它的页面上的表示。首先,在课堂上定义组织原则。在你的情况下,这是第一个字母:
There's a template tag for this, if all you care about is its presentation on the page. First, define an organizational principle in the class. In your case, it's the first letter:
class Item(models.Model):
...
def first_letter(self):
return self.name and self.name[0] or ''
然后使用first_letter调用在模板中定义一个重组:
And then define a regroup in the template, using the first_letter call:
{% regroup items by first_letter as letter_list %}
<ul>
{% for letter in letter_list %}
<li>{{ letter.grouper }}
<ul>
{% for item in letter.list %}
<li>{{ item.name }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
这篇关于Django分组查询由第一个字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!