Django: How to read current select_related() values

This was a bit of a tricky bit of information to get out. The information for select_related() is stored as a nested map. You'll need some recursive code to fetch that back out.

def generate_field_key(map, key, ancestor=None):
values = []
if ancestor:
parent = '%s__%s' % (ancestor, key)
else:
parent = key
values.append(parent)
for k, v in map.items():
values.extend(generate_field_key(v, k, parent))
return values


# Select related is a nested map
qs = Something.objects.all().select_related('hey', 'hey__there')
select_related_data = qs.query.select_related
select_related = []

# This can be a map or False
if select_related_data:
for key, items in select_related_data.items():
select_related += generate_field_key(items, key, None)

print select_related

6uudsa0n9dqhs3ebyzvzlpxm
All good?

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog