按字母顺序过滤的查询

use*_*641 2 python django django-templates django-models django-views

template.html 是

{% for field in types%}
 {{field}}<br />
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Pau*_* Bu 5

如果要按字母顺序排列表单选项,则必须修改获取它们的查询,在表单内,而不是在视图中,因此修改__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
    ...
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!