[Fixed]-Optimizing queries in Django, prefact_related for objects that are reversely linked

1👍

Change your get_organisations code to this:

def get_organisations(self):
    return ', '.join(
        workrelation.group.name for workrelation
        in self.workrelation_set.all()
    )

And use this query for fetching Contact objects:

Contact.objects.prefetch_related('workrelation_set__group')

This will return the result with a single query.

Leave a comment