查询按字母顺序过滤

时间:2013-05-22 07:24:14

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

template.html是

{% for field in types%}
 {{field}}<br />
{% endfor %}

我尝试按字母顺序对列表进行排序。在上面的视图中使用此type_list = Types.objects.filter(user=user.id, parent_type_id=True).order_by('title')进行排序。我不知道我是否正确查询。它没有给出任何错误,但功能没有发生。需要帮助。

由于

2 个答案:

答案 0 :(得分:4)

如果您想按字母顺序排序表单的选项,则必须在表单内部而不是视图中修改获取它们的查询,因此请修改表单的__init__方法中的行这样:

def __init__(self, type_id, *args, **kwargs):
    ...
    type = Types.objects.filter(parent_type_id=type_id).order_by('title')
    MY_CHOICES=((type.id, type.title) for type in type)
    _type_checkbox.choices = MY_CHOICES
    ...

希望这有帮助!

答案 1 :(得分:1)

如果您只需要在渲染模板时进行排序,那么我更喜欢dictsort的简单性。

{% for field in types|dictsort:"title" %}
 {{field}}<br />
{% endfor %}

请注意,它在资本化方面有一些奇怪的行为。我认为它优先考虑大写单词而不是非大写单词,而不是以不区分大小写的方式运作。

相关问题