Alexander Koshkin
Alexander Koshkin

Reputation: 129

Get FK set for each instance in queryset

I have a tree-like Django model say named A, which been done by django-mptt.

class A(MPTTModel):
    parent = TreeForeignKey('self')

this class automaticly has the 'children' manager, so i can easily get the subtree

There is another model, which have FK link to A:

class SomeModel(models.Model):
    link_to_a = models.ForeignKey(A)

I know, that if i want to get SomeModel set of A instance i can do that:

a = A.objects.filter(blah)
a.somemodel_set.all()

and the question is: what is the most pythonic way to fetch somemodel_set of each instance in some queryset under A model, i.e. i want 4 example this:

some_A_instance.children.all().get_all_somemodel_instances()

and get_all_somemodel_instances() should retrieve ziped queryset of sets for each children

Upvotes: 1

Views: 184

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599778

Do you just need the related items in one list, or do you need to associate each set with their parent? If the former, you can get them all at once with this:

related_items = SomeModel.objects.filter(link_to_a=some_A_instance.children.all())

which will do one single query (with a subquery) to get everything.

Otherwise, you can use prefetch_related() to get all items' related sets in one go:

items = some_A_instance.children.all().prefetch_related('somemodel_set')

Upvotes: 1

borges
borges

Reputation: 3687

This should do:

[child.somemodel_set.all() for child in some_A_instance.children.all()]

Upvotes: 0

Related Questions