def get_m2m_field(intermediary_model, related_model):
    """
    Get the field of an intermediary model, that constitutes the
    relation to `related_model`.
    """
    fields = [field for field 
              in intermediary_model._meta.get_fields()
              if field.concrete]
       
    for field in fields:
        if getattr(field, 'target_field', False):
            if field.target_field.model == related_model:
                return field