[Answer]-Speeding up Django backwards relation queries

1👍

I don’t think you need raw SQL here: you should be able to follow the relationship to Succession in the Employee prefetch_related. You shouldn’t need to query Succession separately at all.

employees = Employee.objects.all().prefetch_related('person', 'position', 'succession_set__position')

Now in your template you can just iterate over that:

{% for emp in employees %}
  {{ emp.position.title }
  {% for succ in emp.succession_set.all %}
      {{ succ.position.title }}
  {% endfor %}
{% endfor %}

Leave a comment