简体   繁体   中英

Django - add-up Sum of multiple model fields

How can i add-up the Sum of each Model here? In the end i simply want to have one single value for all up_votes /down_votes accross all 3 models. See example below:

def calc_user_feedback():
    users = User.objects.all()
    try:
        for user in users:
            fed_qry_up_votes = Model1.objects.filter(author=user).aggregate(Sum('up_vote')) + \
                               Model2.objects.filter(author=user).aggregate(Sum('up_vote')) + \
                               Model3.objects.filter(author=user).aggregate(Sum('up_vote'))
            fed_qry_down_votes = Model1.objects.filter(author=user).aggregate(Sum('down_vote')) + \
                               Model2.objects.filter(author=user).aggregate(Sum('down_vote')) + \
                               Model3.objects.filter(author=user).aggregate(Sum('down_vote'))

            logger.info("Overall user feedback calculated successfully.")
    except:
        logger.info("Error processing task: 'Calculate user feedback', please investigate")

Assuming author has no related_name set on each model:

from django.db.models import F, Sum

users = (
    User.objects.annotate(up_votes_1=Sum("model1_set__up_vote"))
    .annotate(up_votes_2=Sum("model2_set__up_vote"))
    .annotate(up_votes_3=Sum("model3_set__up_vote"))
    .annotate(total=F("up_votes_1") + F("up_votes_2") + F("up_votes_3"))
)

Now you can iterate over users and get a total for each one.

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