[Answered ]-Add a column under a condition in django

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 from User_quiz_logs to 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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of user_id.

Leave a comment