I've a queryset result, say, animals, which has a list of animals. There are sub categories of animals and I want to get all the subcategories. i.e.
for single animal, I can use animal.categories
which works. Now, I want to somehow do this:
categories = animals.categories
where animals is queryset. How can I achieve this?
There is no way without iterating over the query set, but you can use prefetch_related
to speed things up:
all_animals = Animals.objects.prefetch_related('categories')
categories = [animal.categories.all() for animal in all_animals]
There are 2 options:
1) Following your question exactly, you can only do:
categories=[]
for aninmal in animals:
categories.extend(animal.categories.all())
2) However, I would run a new query with categories like that (I do not know your exact data model and wording, but I think you get the idea)
categories=Category.filter(animals__in=animals).all()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With