def _get_m2m_reverse_attr(self, related, attr):
        cache_attr = '_m2m_reverse_%s_cache' % attr
        if hasattr(self, cache_attr):
            return getattr(self, cache_attr)
        found = False
        for f in self.rel.through._meta.fields:
            if hasattr(f, 'rel') and f.rel and f.rel.to == related.parent_model:
                if related.model == related.parent_model:
                    # If this is an m2m-intermediate to self,
                    # the first foreign key you find will be
                    # the source column. Keep searching for
                    # the second foreign key.
                    if found:
                        setattr(self, cache_attr, getattr(f, attr))
                        break
                    else:
                        found = True
                else:
                    setattr(self, cache_attr, getattr(f, attr))
                    break
        return getattr(self, cache_attr)
Function that can be curried to provide the related accessor or DB column name for the m2m table
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/models/fields/related.py/ManyToManyField._get_m2m_reverse_attr