1👍
You can .annotate(…)
[Django-doc] with:
from django.db.models import Q, Sum
User.objects.annotate(
points=Sum('user_quiz_logs__points', filter=Q(user_quiz_logs__state_quiz=True))
)
The User
objects that arise from this QuerySet
will have an extra attribute .points
that will contain the total sum of the points
of the related user_quiz_logs
for that User
.
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model fromtoUser_quiz_logs
UserQuiz
.
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: Normally one does not add a suffix
_id
to aForeignKey
field, since Django
will automatically add a "twin" field with an_id
suffix. Therefore it should
beuser
, instead of.user_id