Django – Retrieve all manytomany field objects related to a specific model

Issue

I have my models reviews and news, both having a manytomany relation with Category model.
Now I want to get all the categories associated with only one of these two models. For example, to get all categories associated with News model, I tried querying database with News.categories.all() but got AttributeError: 'ManyToManyDescriptor' object has no attribute 'objects'.

News Model:

class News(models.Model):
    ...
    categories = models.ManyToManyField("articles.Category", related_name="news")
    ...

Reviews Model:

class Reviews(models.Model):
    ...
    categories = models.ManyToManyField("articles.Category", related_name="reviews")
    ...

Solution

You’ll want to retrieve objects through the Category model.
You can filter on the related name on the Category model.

Try Category.objects.filter(reviews__isnull=False) or Category.objects.filter(news__isnull=False)

Answered By – Nico Griffioen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published