Home > OS >  update_create is creating new feilds instead of updating total
update_create is creating new feilds instead of updating total

Time:12-04

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

CodePudding user response:

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

  • Related