Created
September 25, 2014 09:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# <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