Reputation: 5242
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?
Upvotes: 7
Views: 14071
Reputation: 6612
( Base: if animals.categories is giving a queryset that means categories has a many-to-one with animal. and default name (category_set) is changed with categories)
It seems to me like your main query should be a Category query instead of animals. Lets say you get animals like:
Animals.objects.filter(name__startswith='A')
You could get categories of this animals with following query
Category.objects.filter(animal__name__startswith='A')
You can also get animals with this query
Category.objects.filter(animal__name__startswith='A').select_related('category')
But I recommend to use seperate queries for categories and animals (will be more memmory efficent but will do two queries).
Note:If you are really using one-to-many You should consider changing it to many-to-many.
Upvotes: 2
Reputation: 9533
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()
Upvotes: 6
Reputation: 174622
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]
Upvotes: 9