'add a column under a condition in django
This is my model
class User_quiz_logs(models.Model):
user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
user_quiz_id = models.AutoField(primary_key=True)
response = models.CharField('response ', max_length=300, null=False)
points = models.IntegerField('points', null=True)
state_quiz = models.BooleanField('state', default=False)
has an attribute points that I want to add if it corresponds to the same person?
Example
1 A 1 true 141
2 A 1 true 141
3 A 1 true 141
4 B 5 true 165
5 C 1 true 165
The person with id 141 the total sum of his points would be 3 and id 165 would be 6 total points.
Solution 1:[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
toUser_quiz_logsUserQuiz.
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 theUsermodel [Django-doc] directly. For more information you can see the referencing theUsermodel section of the documentation.
Note: Normally one does not add a suffix
_idto aForeignKeyfield, since Django will automatically add a "twin" field with an_idsuffix. Therefore it should beuser, instead of.user_id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
