如何在list()方法内实现部分更新?用UpdateModelMixin更新Wallet余额
如何在ListCreateAPIView的list()方法中批量更新Wallet余额?
你可以通过两种方式实现余额的部分更新,根据数据量选择合适的方法:
方法一:逐个更新(适合少量数据)
在循环中直接为每个Wallet实例赋值balance,调用save()时指定update_fields参数,只更新目标字段,减少数据库开销:
def list(self, request, *args, **kwargs): current_user = request.user wallets = Wallet.objects.filter(user=current_user) balances = get_wallet_balances([wallet.address for wallet in wallets]) for wallet in wallets: # 处理地址不存在的情况,避免KeyError中断流程 balance = balances.get(wallet.address, wallet.balance) wallet.balance = balance # 仅更新balance字段,提升执行效率 wallet.save(update_fields=['balance']) return super().list(request, *args, **kwargs)
方法二:批量更新(适合大量数据)
使用Django的bulk_update()方法,一次性提交所有更新请求,大幅减少数据库交互次数,性能更优:
def list(self, request, *args, **kwargs): current_user = request.user wallets = Wallet.objects.filter(user=current_user) balances = get_wallet_balances([wallet.address for wallet in wallets]) updated_wallets = [] for wallet in wallets: balance = balances.get(wallet.address, wallet.balance) wallet.balance = balance updated_wallets.append(wallet) # 批量提交balance字段的更新 Wallet.objects.bulk_update(updated_wallets, ['balance']) return super().list(request, *args, **kwargs)
注意事项
- 必须处理
balances字典中无对应地址的场景(用get()设置默认值),避免抛出异常中断执行。 - 若Wallet模型有自动更新的时间字段(如
updated_at),批量更新不会触发它,需要的话可以手动赋值后将字段加入更新列表。 bulk_update()要求Django版本≥2.2,旧版本只能使用逐个更新的方式。
内容的提问来源于stack exchange,提问作者Liondancer
相关产品推荐
相关产品推荐

