0

Because I need to avoid a recursive import and work with a Group object as my starting point for my query (which is why I can't import Action objects directly.)

The relationship is Group -> Component -> ComponentVersion -> Action

For instance, Group.components.all() returns all the components in a query set.

Additionally [component.versions.all() for component in Group.components.all()] returns a list of Querysets whose results are all of the versions. Subsequently, .actions.all() would return all the Queryset of actions for each ComponentVersion returned in the comprehension.

What is the optimal way to do this to avoid making unnecessary calls to the DB and for readability?

mburke05
  • 1,371
  • 2
  • 25
  • 38

1 Answers1

2

Prefetch Related start here, this will run 4 queries but will retrieve all the data right away vs iterating and making multiple queries.

Group.objects.all().prefetch_related('components', 'components__versions', 'components__versions__actions')
kevswanberg
  • 2,079
  • 16
  • 21
  • sorry for my misunderstanding, but how do i access the actual `actions` objects? i have something as you had mentioned, `component_qs = Group.components.all().prefetch_related('versions', 'versions__actions')`, so i can do `[component for component in component_qs]` and it returns a list of components as expected. if i for instance attempt `[component.versions.actions for component in component_qs]` i get `RelatedManager object has no attribute actions` – mburke05 Jun 22 '18 at 14:03
  • Yeah since versions is a related manager and not a action you would need to get one version actions at once. Component.versions()[0].actions. Or get the version whatever way you can, you might need to nest the list comprehensions, but at that point there might be more straightforward ways of doing it. – kevswanberg Jun 22 '18 at 18:36