2013-09-26 3 views
2

FaqTopic ID가 주어지면 해당 주제에 대한 질문에 답변 한 응답자의 결과 집합을 얻으려고합니다. 나는 이것이 최소한 두 개의 쿼리를 취할 것이라고 가정하고 있지만, 어떻게해야하는지 완전히 확신 할 수는 없다. 내 모델과 같이 대략 모양 : 각 질문을 통해Django 리버스 manytomany 관계의 쿼리 집합

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

그런 다음 루프를 독특한 respondants의 집합을 구축 :

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) 

그래서 같이 뭔가를 할 수 있습니다. 그러나 그것은 추한 것처럼 보인다.

답변

4

하나의 쿼리에서 수행 할 수 있습니다. 이렇게하면 특정 주제에 대해 질문에 답변 한 응답자를 얻을 수 있습니다. 당신이 topic 객체가있는 경우

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

또는

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

당신은 lookups that span relationships here

+0

아름다운에 대한 자세한 읽을 수 있습니다! 감사. – wmfox3