How to use variables as name of fields in order to update objects dynamically in Django

Viewed 102

there are three fields in the model below in a Django app, just for example.

    class MyModel(models.Model):

        field1 = models.IntegerField(default=0, blank=False,null=False)
        field2 = models.IntegerField(default=0, blank=False,null=False)
        field3 = models.IntegerField(default=0, blank=False,null=False)

In order to update multiple fields, I want to use a variable "target_field" instead of using each name of fields.

    for i in (1,3):
        target_field = "field{0}".format(i)
        sample_value = some_list[i]
        
        sample_object = get_object_or_404(MyModel, id=sample_d)
        sample_object.target_field = sample_value # this couldn't work.
        sample_object.save()

In the code described above, "target_field" is not recognized as a name of fields.

2 Answers

You can set the field of a model just as any other attribute of a class:

for i in (1,3):
    target_field = "field{0}".format(i)
    sample_value = some_list[i]
        
    sample_object = get_object_or_404(MyModel, id=sample_d)
    setattr(sample_object, target_field, sample_value)
    sample_object.save()

You can try using the exec() to get around it.

exec(sample_object+"."+target_field+"='sample value'")

This should work if both sample_object and target_field are strings and the object is created in main. I have used this method to dynamically set values to variables in some of my prior projects.

Related