2013-09-26 113 views
2

给定一个FaqTopic id,我试图得到一个回答的结果集谁回答了关于该主题的问题。我假设这至少需要两次查询,但我不完全确定如何去做。我的模型看起来大致像这样:Django queryset的反向manytomany关系

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() 

然后通过每个问题的循环,并建立了一套独特的respondants的。但那似乎很难看。

回答

4

您可以在一个查询中完成。这会给你一个在特定主题中回答问题的答复者。

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

或者,如果你有一个topic对象,

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

你可以阅读更多的lookups that span relationships here

+0

美丽!谢谢。 – wmfox3