rinti
rinti

Reputation: 1273

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.

Upvotes: 1

Views: 247

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882851

You can use: setattr(obj, fieldname, 'new name').

Upvotes: 5

Related Questions