How to get all children of queryset in django?

11,796

Solution 1

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]

Solution 2

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()

Solution 3

( 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.

Share:
11,796
wasimbhalli
Author by

wasimbhalli

Front-end/Back-end Web Developer

Updated on June 04, 2022

Comments

  • wasimbhalli
    wasimbhalli almost 2 years

    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?

  • wasimbhalli
    wasimbhalli over 11 years
    I, later, use values_list in code, which is not working for categories
  • wasimbhalli
    wasimbhalli over 11 years
    I used categories.values_list('user_id', flat=True) which returns error: 'list' object has no attribute 'values_list'