Cookbook(实用代码片段)(续)
def product_update(*, product: Product, data: dict) -> Product:
"""更新产品信息"""
# 验证
if 'price' in data and data['price'] < 0:
raise ValidationError("Price cannot be negative")
# 更新无副作用字段
basic_fields = ['name', 'description', 'price', 'stock']
product, has_updated = model_update(
instance=product,
fields=basic_fields,
data=data
)
# 处理副作用
if has_updated and 'price' in data:
# 价格变化时,记录历史
PriceHistory.objects.create(
product=product,
old_price=product.price,
new_price=data['price']
)
return product
示例 3:带权限检查的更新