1

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")
3
  • Why exactly did you make three models? If two things are that similar, it is often useful to use the same model. Commented Jan 22, 2020 at 21:00
  • I absolutly with you, but my application has several very complex implementation and i was sadly not able to stay confirm. Im not able to change everything afterward as the code has started like that years ago ... Commented Jan 22, 2020 at 21:15
  • What's the related_name for author on each model? Commented Jan 22, 2020 at 21:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But it also seems that i only get back the number of objects not the number of the actual up_vote/down_vote field if i use count
You don't need to use count, just use the total field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.