Django queryset of reverse manytomany relation

时间:2013-09-26 20:46:07

标签: django

鉴于FaqTopic id,我正在尝试获得一个回答问题的结果集,他们回答了有关该主题的问题。我假设这将至少需要两个查询,但我不完全确定如何做到这一点。我的模型看起来大致如此:

class FaqTopic(models.Model):
    name = models.CharField(max_length=50)

class Respondant(models.Model):
    name = models.CharField(max_length=50)

class Answer(MediaReady):
    text = models.TextField( blank=True )
    respondant = models.ForeignKey( Respondant, blank=True, null=True )

class Question(MediaReady):
    text = models.CharField( max_length=255, blank=True )
    answers = models.ManyToManyField( Answer, blank=True, null=True )
    topic = models.ForeignKey( FaqTopic, blank=True, null=True )

我可以这样做:

topic = FaqTopic.objects.get(pk=topic_id)
questions = topic.question_set.all()

然后循环遍历每个问题并构建一组独特的响应者。但这看起来很难看。

1 个答案:

答案 0 :(得分:4)

您可以在一个查询中执行此操作。这将为您提供在特定主题中回答问题的受访者。

respondants = Respondant.objects.filter(answer__question__topic__name = name)

或者,如果您有topic个对象,

respondants = Respondant.objects.filter(answer__question__topic = topic)

您可以在lookups that span relationships here

上阅读更多内容