Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
def queryset_to_dict(qs, key='pk'):
Given a queryset will transform it into a dictionary based on ``key``.
return dict((getattr(u, key), u) for u in qs)
def distinct(l):
Given an iterable will return a list of all distinct values.
return list(set(l))
def attach_foreignkey(objects, field, qs=None):
Shortcut method which handles a pythonic LEFT OUTER JOIN.
``attach_foreignkey(posts, Post.thread)``
field = field.field
if qs is None:
qs =
qs = qs.filter(pk__in=distinct(getattr(o, field.column) for o in objects))
if select_related:
qs = qs.select_related(*select_related)
queryset = queryset_to_dict(qs)
for o in objects:
setattr(o, '_%s_cache' % (, queryset.get(getattr(o, field.column)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment