Django:覆盖模型.保存()造成完整性

2024-04-27 00:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重写模型上的save方法,以确保新实例正确填充多对多字段。我在重写的方法中做的第一件事是调用super()save方法。但不知何故这导致了完整性错误。有什么想法吗?在

File: models.py
class Bill(models.Model): 
''' A shared bill '''
total_cost = models.DecimalField(max_digits=8, decimal_places=2)
description = models.CharField(max_length=80)
fronting_user = models.ForeignKey(BillsUser,
                                on_delete=models.PROTECT,
                                related_name='fronted_bill_set')
splitting_users = models.ManyToManyField(BillsUser,
                                         related_name='split_bill_set',
                                        through='BillShare',
                                        through_fields=('bill', 'owed_by'))
group = models.ForeignKey(BillsGroup)

def save(self, *args, **kwargs):
    if not self.pk:
        is_new_instance = True
    super(Bill, self).save(self, *args, **kwargs)
    if is_new_instance:
        members = self.group.users.all()
        for bu in members:
            amount = (payer_share_amt(total_cost, len(members)) 
                        if bu == self.fronting_user
                      else share_amt(total_cost, len(members)))
            BillShare.objects.create(owed_by=bu,
                                     owed_to=self.fronting_user,
                                     total_amount=amount,
                                     amount_unpaid=amount)

尝试在管理视图中保存未更改的实例的回溯:

^{pr2}$

Tags: 实例方法selfifmodelssaveamounttotal