0

This is my models:

class ledger1(models.Model):
    name            = models.CharField(max_length=32)
    Closing_balance = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True)

class journal(models.Model):
    Date       = models.DateField(default=datetime.date.today)
    By         = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers')
    To         = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers')
    Debit      = models.DecimalField(max_digits=10,decimal_places=2,null=True)
    Credit     = models.DecimalField(max_digits=10,decimal_places=2,null=True)

And in my views I have done this:

qscb  = journal.objects.filter(By=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date)
qscb2 = journal.objects.filter(To=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) 

total_debitcb = qscb.aggregate(the_sum=Coalesce(Sum('Debit'), Value(0)))['the_sum']
total_creditcb = qscb2.aggregate(the_sum=Coalesce(Sum('Credit'), Value(0)))['the_sum']

if(ledger1_details.group1_Name.balance_nature == 'Debit'):
    closing_balance = opening_balance + total_debitcb - total_creditcb
else:
    closing_balance = opening_balance + total_creditcb - total_debitcb 

I want to store the value of 'closing_balance' into my model field named 'Closing_Balance'....And automatically update it when any changes are made...

Any idea anyone how it is possible in django?

Thank you

2
  • you want save closing_balance into ledger1_details ? Commented Dec 7, 2018 at 7:05
  • Yes...The value of closing_balance which I get from views into "Closing_balance" field of ledger1 model Commented Dec 7, 2018 at 7:06

1 Answer 1

1

you can try:

if(ledger1_details.group1_Name.balance_nature == 'Debit'):
    closing_balance = opening_balance + total_debitcb - total_creditcb
else:
    closing_balance = opening_balance + total_creditcb - total_debitcb 
ledger1_detail = ledger1.objects.get(pk=ledger1_details.pk)
ledger1_detail.Closing_balance = closing_balance
ledger1_detail.save(update_fields=['Closing_balance'])
Sign up to request clarification or add additional context in comments.

6 Comments

can you check value of closing_balance in if else not None? And can you try again, i edit my answer for find instace again.
what version of your Django ?
Django= 2, 0, 6,
you use any with transaction.atomic() in start line of this code? and can you share value of closing_balance in this case ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.