Django模板:在用对象填充页面时如何随机化顺序?

Gra*_*ave 1 html python django python-3.x django-template-filters

我有一个Survey和一个Choice模型,每个调查都有许多与之相关的选择.当我使用所有选项呈现实际的HTML调查页面时,我使用以下Django模板代码:

{% for choice in survey.choice_set.all %}
    <li class="ui-state-default" choice_id={{ choice.id }}>{{ choice.choice_text }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

然而,我不希望每次都以相同的顺序出现选择,而是希望它们以随机顺序填充以减少任何潜在的偏差效应(例如,有人可能更有可能投票选出首先出现在列表中的选项).

如果有一种方法可以在模板本身内执行此操作,那就太棒了,但似乎我更需要在views.py中的后端执行某些操作.我已经试过这个,没有效果:

class DetailView(generic.DetailView):
    model = Survey
    ...
    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        ...
        survey = get_object_or_404(Survey, survey_link__iexact=survey_link)
        ...
        if randomize_choice_order:
            survey.choice_set.order_by('?')
        ...
        return context
Run Code Online (Sandbox Code Playgroud)

知道我怎么能做到这一点?也许我需要开发一个JS函数来在对象已经放置后随机化它们?

lev*_*evi 6

您可以创建自定义模板标记以随机播放结果.

# app/templatetags/shuffle.py
import random
from django import template
register = template.Library()

@register.filter
def shuffle(arg):
    aux = list(arg)[:]
    random.shuffle(aux)
    return aux
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中

{% load shuffle %}
{% for choice in survey.choice_set.all|shuffle %}
Run Code Online (Sandbox Code Playgroud)