How to set django model field by name?

前端 未结 2 1405
天命终不由人
天命终不由人 2020-12-09 15:18

This seems like it should be dead simple, so I must be missing something. I just want to set the value of a field in my model instance by name. Say I have:

c         


        
相关标签:
2条回答
  • 2020-12-09 15:32

    We may have to see more code.

    setattr(f, 'bar', 'BAR')
    

    should work as this is how Django does it internally.

    Make sure you are calling 'save', as well.

    0 讨论(0)
  • 2020-12-09 15:43

    If you modify the value via setattr, you need to remember to save the model after modifying it. I've been bitten in the past where I changed the values but forgot to save the model, and got the same result.

    setattr(f, 'bar', 'BAR')
    f.save()
    
    0 讨论(0)
提交回复
热议问题