wmfox3
wmfox3

Reputation: 2221

Django queryset of reverse manytomany relation

Given a FaqTopic id, I'm attempting to get a result set of respondants who have answered questions on that topic. I'm assuming this will take at minimum two queries, but I'm not entirely sure how to do it. My models look roughly like so:

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 )

I could do something like so:

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

Then loop through each question and build a set of unique respondants. But that seems ugly.

Upvotes: 3

Views: 3065

Answers (1)

karthikr
karthikr

Reputation: 99620

You can do it in one query. This would give you a respondents who have answered a question in a specific topic.

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

Or if you have a topic object,

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

You can read more on lookups that span relationships here

Upvotes: 4

Related Questions