I am storing all many to many fields on an object using this -
m2m_fields = list(model_source_obj._meta.many_to_many)
I want to iterate over this list to make changes to another object of the same type. I have written the code for it as such -
for field in m2m_fields:
model_target_obj.field.add(**something)
However, I keep getting the error model_target_obj class type has no attribute 'field'. How can I fix this?
You're not accessing the field, you're accessing the (non-existent) literal attribute called "field".
You could use getattr:
obj = getattr(model_target_obj, field)
obj.add(**something)
But I suspect that there are better ways to do whatever you are trying to do.