Click here to Skip to main content
15,441,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a django project in which i am using a query set to count the number of items after adding an item and deleting an item.while the adding part works fine,but after deleting the last item in the list it should return zero.but it doesn't.

What I have tried:

Python
def calc_total_qty():
    items=Items.objects.all()
    itemdetails=ItemDetails.objects.all()
    for x in items:
        for y in itemdetails:
            if x.id==y.model_no_id:
                x.total_qty = y.model_no.itemdetails_set.all().count()
                x.save(update_fields=['total_qty'])
Posted
Updated 30-Nov-20 23:53pm
v2
Comments
Richard MacCutchan 30-Nov-20 5:19am    
I don't see any adding or deleting code there. I think you need to provide much more detail.
muneermohd9690 1-Dec-20 5:53am    
thanks for the reply.i have found the solution.anyway i will share the code below.

1 solution

def calc_total_qty():
    for item in Items.objects.annotate(itemdetails_count=Count('itemdetails')):
        item.total_qty = item.itemdetails_count
        item.save(update_fields=['total_qty'])

#this is where items are added.modelmo,description,quantity should be calculated after item_details_save
def add_items_save(request):
if request.method == "POST":
model_no = request.POST.get("model_no")
description = request.POST.get("description")
#total_qty = request.POST.get("total_qty"),total_qty=total_qty
Items_model = Items(model_no=model_no,description=description)
Items_model.save()
return redirect('add_items')
else:
return redirect('add_items')
#this is where item details are added like modelno,serialno,department,empname
def add_items_details_save(request):
items=Items.objects.all()
if request.method == "POST":
serial_no = request.POST.get("serial_no")

model_no_id = request.POST.get("model_no")
model_no=Items.objects.get(id=model_no_id)

name_id = request.POST.get("issued_to")
issued_to= Prosecutions.objects.get(id=name_id)

employee_name=request.POST.get("employee_name")
ItemDetails_model = ItemDetails(serial_no=serial_no, model_no=model_no,issued_to=issued_to,employee_name=employee_name)
ItemDetails_model.save()
calc_total_qty()

return redirect('add_items_details')
else:
return redirect('add_items_details')
def edit_item_details_delete(request,id):
itemdetails = ItemDetails.objects.get(id=id)
itemdetails.delete()
calc_total_qty()
return redirect('edit_item_details')
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900