I have two models: call them questions and answers:
class FacetQuestion(models.Model):
the_question = models.CharField(max_length=50)
class FacetAnswer(models.Model):
question = models.ForeignKey(FacetQuestion)
display_order = models.SmallIntegerField()
the_answer = models.CharField(max_length=1024)
I’d like to present all the questions and answers in one list, with the questions and answers ordered per my choosing:
Q1
A1
A2
A3
Q2
A10
A9
A4
Without creating n+1 database queries or creating silly looking templates.
That’s an easy join for a database guy like myself, but Toto informs us we’re not in SQL land anymore:
select title_short,answer_note from coat_facetquestion
join coat_facetanswer on (coat_facetanswer.question_id=coat_facetquestion.id)
order by coat_facetquestion.id,coat_facetanswer.display_order;
What’s the best way in Django, and what would the template look like?
<ul>
{% for q in questions %}
<li>{{ q.the_question }}</li>
{% for a in q.FacetAnswers_set.all %}
<li>{{ q.the_answer }}</li>
{% endfor %}
{% endfor %}
</ul>
I see an older module that’s a bit on track at django-batch-select. There’s also select_related() which feels like it must be the answer, but if so the documentation is not quite making that clear.
Based on searching other stack exchange answers: for dealing with the hierarchical data, the best seems to be http://django-mptt.github.com/django-mptt/
For simply reducing the number of queries select_related() is a great help.
For displaying the hierarchical result I have not yet found much.