Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update_create is creating new feilds instead of updating total

payments = list((expense
                     .annotate(month=Month('startDate'))
                     .values('month')
                     .annotate(total=Sum('cost'))
                     .order_by('month')))
    
    for i in payments:
        paymentMonths = (i["month"])
        paymentTotal= (i["total"])
        
        obj, created = Payment.objects.update_or_create(
            author=curruser,
            date=paymentMonths,
            total = paymentTotal,
            defaults={"total": paymentTotal},
            )
    totalcost = Payment.objects.filter(author = curruser.id)

enter image description here

Apparently, it should update the (date = 12) total but it is making new ones with the updated value, it might be because the totaldate is diff or maybe I’m wrong it is confusing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe you just need to omit total = paymentTotal from your arguments.

obj, created = Payment.objects.update_or_create(
    author=curruser,
    date=paymentMonths,
    defaults={"total": paymentTotal},
    )

This is because it is querying the DB to see if a Payment with that total already exists, and if it doesn’t, it’s creating a new one. Instead, you want to query Payments with curruser as the author and with date as paymentMonths, while only updating total with the new paymentTotal

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading