Reputation: 9840
I have a many-to-many field called categories
and I would like to get distinct values stored in that field.
The following is my model:
class Book (models.Model):
categories=models.ManyToManyField(Category, related_name = 'categories', blank = True, null=True)
Here is my Category model:
class Category (MPTTModel):
category = models.CharField(max_length=250)
parent = TreeForeignKey('self', blank=True, null=True, related_name='children')
I'd like to get every single one of the categories related to a book. How would I do this?
Upvotes: 3
Views: 4652
Reputation: 53336
If you want to get categories related to one instance of book, do book_inst.category_set.all()
. There will not be duplicates.
But I think, you want to get all Categories
which are related to any Book
, you can do:
Category.objects.filter(categories__in=[Book.objects.all()]).distinct()
Upvotes: 6
Reputation: 7228
Basically, you need a reverse lookup from the category side to check if there is book for that category if yes, add to the resultant query set. Since, the related_name argument in the Book is 'categories', your reverse lookup would look something like this.
Category.objects.filter(categories__in = Book.objects.all())
Upvotes: 0