简体   繁体   中英

How do I save to a field that is specified in a variable?

I want to do something like this:

# models.py

class Model(models.Model):
    name_in_my_model = models.CharField(max_length=100)

# later

fieldname = 'name_in_my_model'

# this is what I want to do somehow:

obj = Model.objects.get(pk=1)
obj.fieldname = 'new name'
obj.save()

Is this possible? I'm making a reusable application, and the user needs to specify a name of a field that is going to be updated by my app.

您可以使用: setattr(obj, fieldname, 'new name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM