Cookbook(实用代码片段)(续)
# common/services.py
from typing import Tuple, Iterable
from django.db import models
def model_update(
*,
instance: models.Model,
fields: Iterable[str],
data: dict
) -> Tuple[models.Model, bool]:
"""
通用模型更新服务
只更新指定的字段,并且只在值实际改变时才保存。
Args:
instance: 要更新的模型实例
fields: 允许更新的字段列表
data: 包含新值的字典
Returns:
(更新后的实例, 是否有字段被修改)
"""
has_updated = False
# 遍历允许更新的字段
for field in fields:
# 检查 data 中是否包含该字段
if field not in data:
continue
# 获取新值
new_value = data[field]
# 获取当前值
current_value = getattr(instance, field)
# 只在值确实改变时才更新
if current_value != new_value:
has_updated = True
setattr(instance, field, new_value)
# 只在有更新时才保存
if has_updated:
# 使用 update_fields 优化 SQL 查询,确保原子性
instance.save(update_fields=fields)
return instance, has_updated