def attach_foreignkeys(*object_sets, **kwargs):
    """
    Shortcut method which handles a pythonic LEFT OUTER JOIN. Allows you to attach the same object type
    to multiple different sets of data.

    ``attach_foreignkeys((posts, Post.author), (threads, Thread.creator), related=['profile'])``

    Works with only ForeignKeys
    """

    related = kwargs.get('related', [])
    database = kwargs.get('database', 'default')

    values = set()

    model = None

    for objects, field in object_sets:
        if not model:
            model = field.field.rel.to
        elif model != field.field.rel.to:
            raise ValueError('You cannot attach foreign keys that do not reference the same models (%s != %s)' % (model, field.field.rel.to))
        # Ensure values are unique, do not contain already present values, and are not missing
        # values specified in select_related
        values.update(distinct(getattr(o, field.field.column) for o in objects if (related or getattr(o, '_%s_cache' % field.field.name, False) is False)))

    if not values:
        return

    qs = model.objects.filter(pk__in=values).using(database)
    if related:
        qs = qs.select_related(*related)
    queryset = queryset_to_dict(qs)

    for objects, field in object_sets:
        for o in objects:
            setattr(o, '_%s_cache' % field.field.name, queryset.get(getattr(o, field.field.column)))
dataset/ETHPy150Open disqus/django-db-utils/dbutils/helpers.py/attach_foreignkeys/original