You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中Bet模型字段求和异常:创建对象时total_amount为0

问题解决:Bet模型total_amount始终为0的原因及修复

问题根源

你在save方法里通过self.__dict__获取euros、rubles、dollars的字段值,但创建新对象时,传入的字段值还未同步到__dict__中,此时__dict__里这些字段仍是默认的0,求和结果自然为0。

修复方案

最直接可靠的方式是直接访问实例的字段属性计算总和,避开__dict__的同步问题:

class Bet(models.Model):
    bet_id = models.AutoField(primary_key=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='bet_event')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    euros = models.IntegerField(default=0)
    rubles = models.IntegerField(default=0)
    dollars = models.IntegerField(default=0)
    total_amount = models.IntegerField(default=0)
    max_amount = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        self.total_amount = self.euros + self.rubles + self.dollars
        super().save(*args, **kwargs)

灵活扩展方案

如果后续需要新增更多货币字段,可通过动态获取字段值的方式避免硬编码:

def save(self, *args, **kwargs):
    currency_fields = ['euros', 'rubles', 'dollars']
    total = 0
    for field_name in currency_fields:
        total += getattr(self, field_name, 0)
    self.total_amount = total
    super().save(*args, **kwargs)

新增货币字段时,只需更新currency_fields列表即可。

内容的提问来源于stack exchange,提问作者Lerokkkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:12:38