Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created February 24, 2011 23:21
Show Gist options
  • Save yuchant/843110 to your computer and use it in GitHub Desktop.
Save yuchant/843110 to your computer and use it in GitHub Desktop.
Find an exact object-m2m match in Python -- no SQL.
"""
Find Exact M2M - Match
=========
Find an exact m2m match for a model.
Just did for fun in response to a stackoverflow question for a data importing issue....
By Yuji Tomita
2/24/2011
"""
def has_exact_m2m_match(match_list, m2m_model, source_model_field, target_model_field):
"""
Get exact Obj m2m match
"""
if isinstance(match_list, QuerySet):
match_list = [x.id for x in match_list]
results = {}
match = set(match_list)
for source, target in \
m2m_model.objects.filter(size__in=match).values_list(source_model_field, target_model_field):
# note: we are accessing the auto generated through model for the sizes m2m
try:
results[source].append(target)
except KeyError:
results[source] = [target]
return bool(filter(lambda x: set(x) == match, results.values()))
# filter any specific objects that have the exact same size IDs
# if there is a match, it means an Obj exists with exactly
# the sizes you provided to the function, no more.
match_list = [1, 2, 3, 4, 5, 6, ] # id's of a potential m2m object addition
m2m_model = MyModel.my_m2m_field.through
source_model_field = 'mymodel'
target_model_field = 'my_m2m_target'
exists = has_exact_match(match_list, m2m_model, source_model_field, target_model_field)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment