[Django]-Getting all unique values stored in a many-to-many field

6👍

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()
👤Rohan

0👍

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())

Leave a comment