How to update database data in Django?
There are many ways in Django to update database data, here are some common methods:
- refresh()
Model.objects.filter(条件).update(字段=新值)
This method can efficiently update a large amount of data, but it won’t trigger Django’s signals, model methods, and uniqueness validation.
- store()
obj = Model.objects.get(条件)
obj.字段 = 新值
obj.save()
This method can trigger Django signals and model methods, but it is not efficient when updating large amounts of data.
- Update existing data or create new data.
obj, created = Model.objects.update_or_create(条件, defaults={'字段': 新值})
This method will attempt to find an object based on conditions, and if found, update its field values. If not found, it will create a new object. It returns a tuple with the first element being the updated or created object, and the second element being a boolean value indicating whether a new object was created.
- update in large quantities
objs = Model.objects.filter(条件)
for obj in objs:
obj.字段 = 新值
Model.objects.bulk_update(objs, ['字段'])
This method efficiently updates and saves all modified object fields back to the database, as opposed to saving each object individually.
Here are some common methods for updating databases, choose the appropriate method based on your actual needs.