Search code examples
djangoormdjango-querysetdjango-2.1

Django many-to-many: Get a list of categories from a list of articles


For the sake of simplicity let's say I only have 3 models: Articles, Categories, Author.

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

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

class Articles(models.Model):
    name = models.CharField(max_length='100')
    author_id = models.ForeignKey(Author)
    categories = models.ManyToManyField(Categories)
    ...

I filter a list of articles by author_id list_article = Articles.objects.filter(author_id=author_id)

My question is, how do I retrieve a list of 'Categories' from that 'list_article'?

Thank you.


Solution

  • You can use in with the list of articles:

    Category.objects.filter(articles__in=list_article)
    

    Or do the joins directly to the author:

    Category.objects.filter(articles__author_id=author_id)