def attach_foreignkey(objects, field, related=[], database='default'):
    """
    Shortcut method which handles a pythonic LEFT OUTER JOIN.

    ``attach_foreignkey(posts, Post.thread)``

    Works with both ForeignKey and OneToOne (reverse) lookups.
    """
    is_foreignkey = isinstance(field, SingleRelatedObjectDescriptor)

    if not is_foreignkey:
        field = field.field
        accessor = '_%s_cache' % field.name
        model = field.rel.to
        lookup = 'pk'
        column = field.column
        key = lookup
    else:
        accessor = field.cache_name
        field = field.related.field
        model = field.model
        lookup = field.name
        column = 'pk'
        key = field.column

    # Ensure values are unique, do not contain already present values, and are not missing
    # values specified in select_related
    values = distinct(getattr(o, column) for o in objects if (related or getattr(o, accessor, False) is False))
    if not values:
        return

    qs = model.objects.filter(**{'%s__in' % lookup: values})\
              .using(database)
    if related:
        qs = qs.select_related(*related)
    queryset = queryset_to_dict(qs, key=key)
    for o in objects:
        setattr(o, accessor, queryset.get(getattr(o, column)))
dataset/ETHPy150Open disqus/django-db-utils/dbutils/helpers.py/attach_foreignkey/original