我有两个模型Bill和每个有3个字段。这里我想在用户支付账单时直接更新字段last_price。如果用户支付全额,那么它将是0。或者如果用户没有支付全部金额,那么剩余金额要保存在last_price中. 所以这里我想在用户支付账单时直接更新last_bill的金额。
注意:两个模型都在单独的应用
My Fields are:
<BillApp/模型/strong>
Bill(model.Model):
bill_no = models.IntegerField(max_length = 100,primary_key=True)
last_price = models.IntegerField()
Name = models.CharField(max_length = 20)
<PaymentApp/模型/strong>
Payment(model.Model):
id = models.CharField(max_length = 100,primary_key=True)
bill_no = models.ForeignKey(Bill, on_delete = SET_NULL,null=True)
total_amount = models.CharField(max_length = 10)
def save(...):
Update value of Bill.last_price
如何更新Bill.last_price的值在save方法
中我尝试了这个更新字段last_price
def save(self,*args, **kwargs):
new_last_price = self.total_amount - self.bill_no.last_price
print("new_last_price : ",new_last_price)
bill_detail = Bill.objects.filter(bill_no=self.bill_no).first()
print("bill_detail : ",bill_detail)
try:
with transaction.atomic():
updated_field = bill_detail.save(update_fields = ['last_price'])
print("updated_field : ", updated_field)
super().save(*args, **kwargs)
print(Bill.objects.filter(bill_no=self.bill_no).first().last_price)
except IntegrityError:
print('Exception in save')
I得到new_last_price和bill_detail的正确输出..butupdated_field display None ..我如何在Bill中保存新值?
您的save方法将保存数据并刷新对象实例,但不会返回对象实例。直接显示最新价格
bill_detail.save(update_fields = ['last_price'])
print(bill_detail.last_price)