Skip to content
Advertisement

Update Query list in Django

I’m having a trouble on how can I automatically update my amount_unpaid when the time I updated my amount_paidcolumn. The result of amount_unpaid should be subtract my amountamount_paid = amount_unpaid . The way I updated my data is using list like the code below, please check this out, Any help is much appreciated Thanks in advance.

AttributeError: ‘QuerySet’ object has no attribute ‘amount’

enter image description here

def update_remarks(request):
    product_ids = request.POST.getlist('id[]')
    amt_paid = request.POST.get('amount_paid')

    for id in product_ids:
        unpaid_update = (Person.objects.filter(pk=id).amount - amt_paid) #Error no attribute Amount 
        Person.objects.filter(pk=id).update(amount_paid =  unpaid_update) # this should update every amount_unpaid  based on subtracted amount column
        Person.objects.filter(pk=id).update(amount_paid = amt_paid)

Advertisement

Answer

I think the minimalist solution is:

from django.db.models import F

def update_remarks(request):
    product_ids = request.POST.getlist('id[]')
    amt_paid = int(request.POST.get('amount_paid', 0))
    Person.objects.filter(pk__in=product_ids).update(amount_paid=amt_paid, amount_unpaid=F('amount')-amt_paid)

I am using F(<field_name>) to get the value of the field from that object. Hence I do not need a for loop.

For more information, please see the documentation on update(...) and F().

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement