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") ...
Advertisement
Answer
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)