I want to update Contract_bills_amount
field value in Class Contract
from bills_mount
field value in Class Bills
:
#Contract
class Contract(models.Model):
Contract_code = models.CharField(max_length=200)
Contract_rec = models.DateTimeField('contract date ')
Contract_total_amount = models.FloatField('total amount')
Contract_deposit= models.FloatField('deposit')
Contract_remainder_amount=models.FloatField('Contract remainder amount',null=True,blank=True)
Contract_bills_amount=models.FloatField('bills_amount',null=True,blank=True)
Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE)
Contract_car = models.ForeignKey(Car, on_delete=models.CASCADE)
def save(self, *args,**kwargs):
a=self.Contract_total_amount
b=self.Contract_deposit
self.Contract_remainder_amount=a-b
super(Contract,self).save(*args,**kwargs)
def __str__(self):
return self.Contract_code
#Bills
class bills(models.Model):
bills_Contract = models.ForeignKey(Contract, on_delete=models.CASCADE)
Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE)
bills_code = models.CharField(max_length=200)
Contract_rec = models.DateTimeField('date')
bills_mount= models.FloatField('amount')
def __str__(self):
return self.bills_code
CodePudding user response:
You already have a foreign key relationship between Contract and Bills as "bills_Contract
". What else are you looking for? You only need to reference the value of the related table.
Example:
one_contract = Contract.objects.get(pk=1) #get the first contract
all_bills = one_contract.bills_set.all() #get all the bills in the first contract
desired_bill = all_bills.filter(bills_mount=400) #get bills amounting to 400
So, you may not need the "Contract_bills_amount
" field in Contracts at all since you can already access that through backward relationship.
I see you have a reference to the Client in both Contract and Bills (perhaps for convenience but that cyclic reference is not necessary since the Contract Models identifies the owner.)
This relationship (i.e Bill --> Contract --> Client
) implies that you also get the Bill from the client, like so: Bill <-- Contract <-- Client
.
You need to learn more about referencing related objects in django