Skip to content

Instantly share code, notes, and snippets.

@nigma
Forked from dcramer/gist:550435
Created October 23, 2010 12:26
Show Gist options
  • Save nigma/642152 to your computer and use it in GitHub Desktop.
Save nigma/642152 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