Cookbook(实用代码片段)(续)
# 进阶:引入脏检查 (Dirty Check)
def efficient_update(instance, fields, data):
has_updated = False
for field in fields:
if field in data:
new_value = data[field]
current_value = getattr(instance, field) # 先“看一眼”旧值
# 只有真的变了,才动手
if current_value != new_value:
setattr(instance, field, new_value)
has_updated = True
if has_updated:
# ✅ 精准写入:只更新 fields 中指定的列,不干扰其他字段。
# 这也解决了 Race Condition(多个进程同时改不同字段导致互相覆盖)的问题。
instance.save(update_fields=fields)
return has_updated
model_update 的底层实现
这是我们根据上述思路打造出的“通用武器”。建议将其放在项目的 common/services.py 中。