Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all children of queryset in django?

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?

like image 545
wasimbhalli Avatar asked Aug 27 '12 11:08

wasimbhalli


2 Answers

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]
like image 172
Burhan Khalid Avatar answered Nov 03 '22 01:11

Burhan Khalid


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()
like image 34
schacki Avatar answered Nov 02 '22 23:11

schacki