Skip to content

Instantly share code, notes, and snippets.

@dcramer
Created August 25, 2010 22:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dcramer/550435 to your computer and use it in GitHub Desktop.
Save dcramer/550435 to your computer and use it in GitHub Desktop.
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 = field.rel.to.objects.all()
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' % (field.name), queryset.get(getattr(o, field.column)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment