Search code examples
djangofunctionparametersmodelmany-to-many

a way to pass m2m field and action into a function's parameter? django


Let's say I have a model which has a m2m field named best.

I know by adding things into the best field we can do something like model.best.add(blah) or remove model.best.remove(blah)

if I have another m2m field named worst and I want to make a function which will then use the parameter to define if I should be using the best or worst field and if the action is add() or remove

Is if possible?

I already tried something silly such as:

def change(field, action, obj):
    model.field.action(obj)

of course the above will not work, is there a way to make this work so I do not need to do lots IF if I have LOTS m2m fields in one model?

Thanks in advance for any advices


Solution

  • figured using getattr would work well such as getattr(model, field) this way even if I don't use action for the function, still lots less code to write and better if I have new fields added