Reputation: 31
I have dozens of fields in a Django model.
class Question(models.Model):
op1 = models.CharField(verbose_name="Option 1",max_length=500,null=True,blank=True)
op2 = models.CharField(verbose_name="Option 2",max_length=500,null=True,blank=True)
op3 = models.CharField(verbose_name="Option 3",max_length=500,null=True,blank=True)
....
I want to write a function
def update_ith_option_of_question( q, i, val):
op = d._meta.get_field('op'+str(i))
# I want to save val in field op of object q
How do I write the above function?
Upvotes: 0
Views: 21
Reputation: 5443
Use Python's setattr
.
def update_ith_option_of_question(q, i, val):
setattr(q, f'op{i}', val)
q.save()
Also, using f''
strings for formatting is more readable.
Upvotes: 1