It is almost impossible to answer without seeing the definition of the model. If this is a ForiegnKey relationship, you can most likely completely eliminate the outer loops and just generate all your data by following the foreign keys up (using select_related, of course, to get all the data at once)
However, most likely, we are looking at many many relationships, and for this you cannot just move the backups of foreign keys, and the answer you have may be the best you can do.
source share