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()
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())
- [Django]-Django sitemap static pages
- [Django]-Mod_wsgi (3.4-14) / Apache 2.4.12 / Red Hat (6.7) / Django 1.8.2 hanging under load
- [Django]-Storing multiple values into a single field in mysql database that preserve order in Django
Source:stackexchange.com