【发布时间】:2016-05-29 09:46:57
【问题描述】:
我的模型中实际上有这个方法:
def speed_score_compute(self):
# Speed score:
#
# - 8 point for every % of time spent in
# high intensity running phase.
# - Average Speed in High Intensity
# running phase (30km/h = 50 points
# 0-15km/h = 15 points )
try:
high_intensity_running_ratio = ((
(self.h_i_run_time * 100)/self.training_length) * 8)
except ZeroDivisionError:
return 0
high_intensity_running_ratio = min(50, high_intensity_running_ratio)
if self.h_i_average_speed < 15:
average_speed_score = 10
else:
average_speed_score = self.cross_multiplication(
30, self.h_i_average_speed, 50)
final_speed_score = high_intensity_running_ratio + average_speed_score
return final_speed_score
我想像这样将它用作我的模型的默认值:
speed_score = models.IntegerField(default=speed_score_compute)
但这不起作用(请参阅下面的错误消息)。我检查了不同的主题,例如 this one,但这仅适用于函数(不使用 self 属性)而不适用于方法(我必须使用方法,因为我正在使用实际的对象属性)。
Django doc. 似乎在谈论这个,但我不太清楚可能是因为我还是 Django 和 Programmation 的新手。
有没有办法做到这一点?
编辑:
我的功能在我的模型之上定义。但这是我的错误信息:
ValueError: Could not find function speed_score_compute in tournament.models.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared and used in the same class body). Please move the function into the main module body to use migrations.
For more information, see https://docs.djangoproject.com/en/1.8/topics/migrations/#serializing-values
错误信息很清楚,我似乎无法做到这一点。但是还有其他方法可以实现吗?
【问题讨论】:
-
我的
speed_score_compute()函数定义在speed_score模型之上。 -
“但这不起作用”意味着什么?错误?结果无效?
-
问题已更新为我的错误消息。
-
我有很多关于分数计算的方法,我只是在这里放一个以保持问题清楚。如果我删除
activity_score_compute()方法,将有与speed_score_compute()相同的消息。我将编辑以将 speed_score 放在一个以避免混淆。 -
@Addict 我可以修改您的问题以使其更通用和规范,以便任何提出相同问题的人都可以轻松引用它吗?
标签: python django django-models django-rest-framework