Query ManyToMany relations without a named through field

Go To StackoverFlow.com


I have this setup in my models:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Topic(models.Model):
    name = models.CharField(max_length=100)

class Article(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author, null=True, blank=True)
    topics = models.ManyToManyField(Topic, null=True, blank=True)

Given an author, I want to know which topics he wrote about:

def author_info(request, pk):
    author = get_object_or_404(Author, pk=pk)
    topics = ????

If I had specified a through field, I could use that, but now Django makes the through field for me, and since its supposed to be transparent, Id rather not reference the field (unless there is a proper Django construction for that).

2012-04-04 07:08
by dyve


Use Lookups that span relationships:

topics = Topic.objects.filter(article__authors=author).distinct()

Note: you have to use distinct here, because the same topic can be selected by different articles.

2012-04-04 07:31
by jpic
Thanks! I should have been able to find that myself, but apparently I missed it. Gonna check it out now - dyve 2012-04-04 09:22
Like a charm. Thanks - dyve 2012-04-04 09:26