How to get all children request in django?

I have a query result, say, of animals that has a list of animals. There are subcategories of animals, and I want to get all the subcategories. i.e.

for one animal, I can use animal.categories , which works. Now I want to do this somehow:

 categories = animals.categories 

where animals are a request. How can I achieve this?

+4
source share
3 answers

There is no way without iterating over a set of queries, but you can use prefetch_related to speed up the process:

 all_animals = Animals.objects.prefetch_related('categories') categories = [animal.categories.all() for animal in all_animals] 
+4
source

There are 2 options:

1) According to your question, you can do the following:

 categories=[] for aninmal in animals: categories.extend(animal.categories.all()) 

2) However, I would run a new query with such categories (I do not know your exact data model and wording, but I think you understand)

 categories=Category.filter(animals__in=animals).all() 
+5
source

( Base : if animal.categories sets up a query, which means that the categories are many-to-one with animals, and the default name (category_set) is changed using categories)

It seems to me that your main query should be a category query instead of animals. Let's say you get animals such as:

 Animals.objects.filter(name__startswith='A') 

You can get categories of these animals with the following query

 Category.objects.filter(animal__name__startswith='A') 

You can also get animals with this request

 Category.objects.filter(animal__name__startswith='A').select_related('category') 

But I recommend using separate queries for categories and animals (it will be more efficient, but will make two queries).

Note If you really use one-to-many, you should consider changing it for many-to-many.

+2
source

All Articles