I am using Django to generate a template formatted as a plist to be directly used within an iPhone app. However, I am having trouble getting the plist to output correctly based on my database. Essentially, I have a table containing tests. Each with a testID and a test_type. The table uses the unique_together clause to make sure no two entries have the same testID and test_type and it also orders results by testID and test_type. But in my template, I’d like to group all of the tests with the same testID within the same dictionary.
My template looks something like this:
<?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>
Essentially, I wanted the {% if changed %} directive to evaluate based on the the last time it evaluated, not within the same loop. But of course this isn’t the actual behavior, because it naturally checks its values based on the last loop iteration. How should I produce my desired output? Also, the tests array is generated via:
tests = Test.objects.annotate(num_questions=Count('questions')).filter(num_questions__gt=0).all()
The {% ifchanged %} should work if the “tests” set is ordered by testID.
Have you tried:
You can also take a look at {% regroup %} tag.
[updated]
How about a couple tests for forloop.{first,last}? (sorry, untested…)