[英]How can I add two different integer fields of the same model in Django
class Score(models.Model):
Score_A=models.IntegerField()
Score_B=models.IntegerField()
How can I put the sum of these two fields into another field?如何将这两个字段的总和放入另一个字段?
The best solutions for this create a trigger in a database that stores a total of the two fields in another field.对此的最佳解决方案是在数据库中创建一个触发器,该触发器将两个字段的总数存储在另一个字段中。
I would really advise not to store the sum of the two fields, but simply annotate the queryset.我真的建议不要存储两个字段的总和,而只是注释查询集。 That way you avoid data duplication , which will make the database slightly larger, but more important, it will be quite hard to keep the fields in sync.
这样可以避免数据重复,这会使数据库稍微变大,但更重要的是,保持字段同步会非常困难。
from django.db.models import F
Score.objects.annotate(Score_total=F('Score_A')+F('Score_B'))
the Score
objects that arise from this queryset will have an extra attribute Score_total
, which is the sum of the two fields.从这个查询集中产生的
Score
对象将有一个额外的属性Score_total
,它是两个字段的总和。
Note : normally the name of the fields in a Django model are written in snake_case , not PerlCase , so it should be:
score_a
instead of.Score_A
注意:通常 Django model 中的字段名称是用snake_case 写的,而不是 PerlCase ,所以它应该是:
score_a
而不是。Score_A
The problem with the solutions people presented is that they work with the database, This adds some overhead, You want to do something like this人们提出的解决方案的问题是他们使用数据库,这增加了一些开销,你想做这样的事情
class Score(models.Model):
Score_A = models.IntegerField()
Score_B = models.IntegerField()
def overall_score(self):
return self.Score_A + self.Score_B
This won't alter the database, This may have some side effects like RACE CODITIONS , Be sure to use select_for_update
or whatever way you prefer to lock the DB
when using the Score
model.这不会改变数据库,这可能会产生一些副作用,例如RACE CODITIONS ,请务必使用
select_for_update
或在使用Score
model 时锁定DB
的任何方式。
I'd like to mention that you should stick with pep8, score_a
, score_b
我想提一下,你应该坚持使用 pep8,
score_a
, score_b
You can override the save method so when a record is created or updated the value of the sum will be saved like below您可以覆盖 save 方法,因此当创建或更新记录时,总和的值将如下所示
class Score(models.Model):
Score_A=models.IntegerField()
Score_B=models.IntegerField()
sum=models.IntegerField()
def save(self, *args, **kwargs):
self.sum = self.Score_A +self.Score_B
super(Score, self).save(*args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.