I've got some nested models
class Category(models.Model):
name = models.CharField()
class FacetQuestion(models.Model):
category = models.ForeignKey(Category)
description = models.CharField()
class FacetAnswer(models.Model):
question = models.ForeignKey(FacetQuestion)
answer = models.CharField()
subject = models.SmallIntegerField(default=1)
I can efficiently get all the answers/questions/categories at least in the view:
def detail(request, id):
facets= models.Category.objects.
filter(facetquestion__facetanswer__subject='test').
select_related()
return render_to_response('test.tpl',
dict(facets=facets,
STATIC_URL = settings.STATIC_URL,
MEDIA_URL = settings.MEDIA_URL),
context_instance=RequestContext(request))
But when I loop though them in a template, I get everything (not just what I filtered on), because the template makes additional queries for all questions and all answers. So the template code is definitely bogus:
{% for category in answers %}
{% for q in category.facetquestion_set.all %}
{% for a in q.facetanswer_set.all %}
{% endfor %}
{% endfor %}
{% endfor %}
What's a good pattern for showing a nested set of models in logical order?
Category
Question
Answer (subject=test)
Answer (subject=test)
Question
Answer (subject=test)
Category
Question
Answer (subject=test)
I am using django 1.3. I asked a similar question here, but that one did not include filtering by subject.