3

I'm using the app django-mptt to store a small tree structure. In django view, how can I query the entire table in a single query, to get a queryset/list with each instance having a children attribute?

So I would like to do:

groups = SongGroup.objects.all().values()
for group in groups:
   group['children'] # list of children

But as I see in the docs, get_children() will trigger another query? Which I want to avoid, since I've already used all() to query the entire table.

I couldn't find a way in the docs to get an actual tree like structure from the table.
My model:

class SongGroup(MPTTModel):
    song = models.ForeignKey(Song, on_delete=models.CASCADE)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
user3599803
  • 6,435
  • 17
  • 69
  • 130
  • Use `SongGroup.objects.all().prefetch_related('children')` and use `group.children.all()` this won't query again, this is a eager loading not lazy load. So this is optimized, but if you use `filter()` instead of `all()` it will become lazy load and that will be bad. Another option query and use recursion to get tree like structure in dictonary. – Anup Yadav Mar 30 '18 at 10:19
  • how much levels prefetch_related will get? – user3599803 Mar 30 '18 at 11:09
  • All levels related to `children` which has this relation, don't worry this should work regardless of levels – Anup Yadav Mar 30 '18 at 11:10

0 Answers0