Home > Software design >  django changing a value of databe field using variable in view
django changing a value of databe field using variable in view

Time:11-28

Is there any way to update the by-hand value of a particular field in the model instance using variables?

For example.

models.py

class ExampleModel(models.Model):
        name=models.CharField(max_length=10)
        a=models.CharField(max_length=10)
        b=models.CharField(max_length=10)
        c=models.CharField(max_length=10)

views.py

list=[a,b,c]
fruits=[orange,apple,banana]
values
def ExampleView(request):
    model_instsnce=ExampleModel.objects.last()
    for i in list:
    instance_model.i=fruits[i]
    model_instance.save()

In my project, I tried to use something like the above but it doesn't work. 'i' from loop doesn't behave like a variable. 'i' is treated as a new field in the model.

Any idea how to use variables to designate fields from model to change?

CodePudding user response:

Since django models are essentially just objects, the model fields are just attributes. As such, you could simply use a dict to map the field-value pairs you want to update for the model and then call setattr to set them:

# store/get the model field-value pair data
fruits = {
    'a': 'orange',
    'b': 'apple',
    'c': 'banana'
}

def ExampleView(request):
    model_instance = ExampleModel.objects.last()
    # update the model fields
    for key, value in fruits.items():
        setattr(model_instance, key, value)
    model_instance.save()

I'm assuming that you're getting the update values dynamically as well so you'd have to adjust the above code for that, but overall I think this addresses the main point of your question.

References

  • Related