Home > Software design >  add a column under a condition in django
add a column under a condition in django

Time:03-24

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.

CodePudding user response:

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.

  • Related