我正在使用Django生成格式化为plist的模板,以便直接在iPhone应用程序中使用。但是,我无法根据我的数据库正确输出plist。基本上,我有一个包含测试的表。每个都有一个testID和一个test_type。该表使用unique_together子句确保没有两个条目具有相同的testID和test_type,并且它还通过testID和test_type对结果进行排序。但是在我的模板中,我想在同一个字典中使用相同的testID对所有测试进行分组。 我的模板看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>all_tests</key>
<array>
{% for t in tests %}
{% ifchanged t.testID %}<dict>
<key>testID</key>
<string>{{ t.testID }}</string>
<key>sections</key>
<array>{% endifchanged %}
<dict>
<key>pk</key>
<integer>{{ t.pk }}</integer>
<key>type</key>
<string>{{ t.test_type }}</string>
<key>num_questions</key>
<integer>{{ t.num_questions }}</integer>
</dict>
{% ifchanged t.testID %}</array>
</dict>{% endifchanged %}{% endfor %}
</array>
基本上,我希望{%if changed%}指令根据它上次评估的时间来评估,而不是在同一个循环中。但当然这不是实际行为,因为它会根据最后一次循环迭代自然地检查其值。我该如何产生我想要的输出?此外,tests数组通过以下方式生成:
tests = Test.objects.annotate(num_questions=Count('questions')).filter(num_questions__gt=0).all()
答案 0 :(得分:1)
如果testID命令“tests”设置,{%ifchanged%}应该有效。
你试过了吗?
tests = Test.objects\
.annotate(num_questions=Count('questions'))\
.filter(num_questions__gt=0)\
.order_by('testID').all()
您还可以查看{% regroup %}代码。
[更新]
forloop的几个测试怎么样。{first,last}? (对不起,未经测试......)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>all_tests</key>
<array>
{% for t in tests %}
{% ifchanged t.testID %}
{% if not forloop.first %}
</array>
</dict>
{% endif %}
<dict>
<key>testID</key>
<string>{{ t.testID }}</string>
<key>sections</key>
<array>{% endifchanged %}
<dict>
<key>pk</key>
<integer>{{ t.pk }}</integer>
<key>type</key>
<string>{{ t.test_type }}</string>
<key>num_questions</key>
<integer>{{ t.num_questions }}</integer>
</dict>
{% if forloop.last %}
</array>
</dict>
{% endif %}
</array>