balaq
balaq

Reputation: 13

How to get field from django model by name from list

I got model like:

class mymodel(models.Model):
    val1 = models.FloatField(default=0)
    val2 = models.FloatField(default=0)
    ...and more var with other names
    name = models.CharField(max_length=200)
    url = models.CharField(max_length=200)

I need change values in many models but not all fields (only from list)

list= ['val1', 'val2' .... 'val15']
for entry in list:
    mymodel.entry = data[entry]

How can i do it? i tried {entry}, entry, [entry]

Upvotes: 1

Views: 95

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can work with setattr [python-doc] to set an attribute. This thus means that setattr(x, 'y', z) is equivalent to x.y = z, so you can work with:

mylist = ['val1', 'val2' .... 'val15']
for entry in mylist:
    setattr(mymodel, entry, data[entry])

beware that mymodel here should be a model object, not the class, since otherwise you are destroying the fields defined on the class, and not creating records at the database.

Upvotes: 1

Related Questions