0

I have two models Bill and Payment each with 3 fields. Here I want to update field last_price directly when user pay bill. If user pay complete amount then it would be 0. or if user not pay complete amount then remaining amount want to be save in last_price. So here I want to update amount of last_bill directly when user pay bill.

Note: Both models are in separate app

My Fields are:

BillApp/models

 Bill(model.Model):
      bill_no = models.IntegerField(max_length = 100,primary_key=True)
      last_price = models.IntegerField()
      Name = models.CharField(max_length = 20)

PaymentApp/models

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

How do I update value of Bill.last_price in the save method

I tried this for update field 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 getting correct output of new_last_price and bill_detail.. but updated_field display None .. How Can I save new value in Bill?

1 Answers1

0

Your save method will save the data and refresh the object instance but will not return the object instance. Use directly show last price.

bill_detail.save(update_fields = ['last_price'])
print(bill_detail.last_price)
Ashin Shakya
  • 690
  • 6
  • 9