简体   繁体   中英

Django for loop looping only once through queryset

I'm working on a project and I ran into one problem. I'm looping through a queryset and the for loop is running only once without giving any error. This problem was not happening earlier but now it came out of nowhere. below is my code.

views.py

ward = Student.objects.get(id = request.POST.get('ward'))
request.session['student'] = request.POST.get('ward')
fees = Fee.objects.get(classes = ward.classes)
extras = ExtraFee.objects.filter(student = ward)
ex = ExtraFee.objects.filter(student = ward).values('title').annotate(Count('title'))
print(ex)
for e in ex:
    print(e)
    title = e['title']
    if e['title__count'] > 1:
       print(title)
       extra = ExtraFee.objects.filter(title = e['title'], student = ward)
       amount = 0
       fine = 0
       for ex in extra:
         amount = int(ex.amount) + amount
         total = amount
       for exs in extras:
         fine = int(exs.amount) + fine
         totalfine = fine
         return render(request, "dashboard/parent_fees.html", {"students": students, "parent": parent, "ward": ward, "fees": fees, "extras": extras, "totalfine": totalfine, "total": total, "title": title})
    else:
      fine = 0
      for e in extras:
         fine = int(e.amount) + fine
         totalfine = fine
         return render(request, "dashboard/parent_fees.html", {"students": students, "parent": parent, "ward": ward, "fees": fees, "extras": extras, "totalfine": totalfine})

Thanks in advance for your time and help.

Using a return inside of a loop, will break it and exit the method/function even if the iteration still not finished.

So never use 'return' inside a loop unless you know what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM