在django中的条件下添加一列
add a column under a condition in django
这是我的模型
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)
有对应同一个人的属性点要加吗?
例子
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
id 141 的人他的积分总和为 3,id 165 的总积分为 6。
您可以 .annotate(…)
[Django-doc] 使用:
from django.db.models import <b>Q, Sum</b>
User.objects.annotate(
<b>points=Sum('user_quiz_logs__points', filter=Q(user_quiz_logs__state_quiz=True))</b>
)
由此QuerySet
产生的User
对象将有一个额外的属性.points
,它将包含相关[=15]的points
的总和=] 那个 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
.
这是我的模型
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)
有对应同一个人的属性点要加吗?
例子
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
id 141 的人他的积分总和为 3,id 165 的总积分为 6。
您可以 .annotate(…)
[Django-doc] 使用:
from django.db.models import <b>Q, Sum</b>
User.objects.annotate(
<b>points=Sum('user_quiz_logs__points', filter=Q(user_quiz_logs__state_quiz=True))</b>
)
由此QuerySet
产生的User
对象将有一个额外的属性.points
,它将包含相关[=15]的points
的总和=] 那个 User
.
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
toUser_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