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

i have a proplem with django python

comments = project.masarif.filter(active=True)
def sub_masarif():
    for sub in comments:
        total = 0
        xdd = sub.count
        total += (xdd)
        print(total) # 3 4 69 

i need sum total < example print(total) # 76

>Solution :

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

You each time reset total, hence it each time prints the current value. You should set the total = 0 variable outside the loop, so:

def sub_masarif():
    total = 0
    for sub in project.masarif.filter(active=True):
        xdd = sub.count
        total += sub.count
    print(total)

But you here aggregate at the Django/Python layer. Normally it is better to do this at the database side, so:

from django.db.models import Sum

def sub_masarif():
    total = project.masarif.filter(active=True).aggregate(total=Sum('count'))['total']
    print(total)
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