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:
JavaScript
x
5
1
class News(models.Model):
2
3
categories = models.ManyToManyField("articles.Category", related_name="news")
4
5
Reviews Model:
JavaScript
1
5
1
class Reviews(models.Model):
2
3
categories = models.ManyToManyField("articles.Category", related_name="reviews")
4
5
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)