[Answered ]-Django- how to update using arguments, i can update normally like first assigning,then Model.save

2👍

âś…

What @San4ez proposes is correct.

Keep in mind though that the .save method of a Model flushes/rewrites the entire row back at the database even if you want to change only one column/field.

An alternative method that provides better performance and concurrency is by using
the Queryset’s update method, which only updates the selected columns.

So provided that “name” has a unique constraint(so that filter will return only one result).

Modelname.objects.filter(name="ramesh").update(**mydict)

There is work being done right now so that future versions of django can
provide this functionality on the .save method. See more here

EDIT: Worth noting is the fact that should you choose to use the above method, any post/pre signals won’t be emitted by django and generally the .save method of the model won’t be called, as per django’s documentation.

👤rantanplan

0👍

m = Modelname.objects.get(name="ramesh")
for key, value in data.items():
    if key in keys:
        setattr(m, key, value)
m.save()
👤San4ez

Leave a comment