-
-
Save nigma/642152 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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