Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Created September 25, 2014 09:09
Show Gist options
  • Save kezabelle/c0b052898e660f22982c to your computer and use it in GitHub Desktop.
Save kezabelle/c0b052898e660f22982c to your computer and use it in GitHub Desktop.
How to get the PKs of an m2m, when you know the field name but not the related name.
# <model_instance> = a model, eg: MyModel.objects.get(pk=?)
# <m2m_name> = the field name defined in the model as a ManyToManyField
field_to_filter_by = <model_instance>.__class__.<m2m_name>.field
fieldname_to_filter_by = field_to_filter_by.related.var_name
filter_kwargs = {
fieldname_to_filter_by: <model_instance>,
}
m2m_model = <model_instance>.<m2m_name>.through
just_my_m2ms = m2m_model.objects.filter(**filter_kwargs)
pks_of_m2ms = frozenset(just_my_m2ms.values_list('pk', flat=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment