我有一些嵌套模型
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)
我至少可以在 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))
但是,当我在模板中循环访问它们时,我得到了所有信息(不仅仅是我过滤的信息),因为模板对所有问题和所有答案都进行了附加查询。因此,模板代码肯定是伪造的:
{% for category in answers %}
{% for q in category.facetquestion_set.all %}
{% for a in q.facetanswer_set.all %}
{% endfor %}
{% endfor %}
{% endfor %}
以逻辑顺序显示一组嵌套模型的好模式是什么?
Category
Question
Answer (subject=test)
Answer (subject=test)
Question
Answer (subject=test)
Category
Question
Answer (subject=test)
我正在使用django 1.3。我问了一个类似的问题here,但这个问题不包括按主题过滤。
最佳答案
我不知道如何解决您的问题,但我想我可以告诉您您哪里出了问题。
用这条线
answers = models.Category.objects.filter(facetquestion__facetanswer__subject=2)
您正在选择所有具有一个或多个问题的类别,这些问题具有一个或多个
subject == 2
的答案。当您像这样遍历所选类别时:
{% for category in answers %}
{% for q in category.facetquestion_set.all %}
{% for a in q.facetanswer_set.all %}
在每个循环中,您都会向发出另一个查询,以获取类别中的所有问题(
category.facetquestion_set.all
)和该问题的所有答案(q.facetanswer_set.all
)。不论过滤器。
您可以使用此代码段以DEBUG模式打印SQL并了解幕后情况:http://djangosnippets.org/snippets/93/
...而且在这种情况下,我猜它会打印很多SELECT。
关于django - 过滤然后遍历嵌套的Django模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9505164/