表单在 def save 中解释为 0。重构我的解决方案



我在模型表单中有所有这些单选组和真正的错误复选框。如果未选中复选框或未选中单选组中的按钮,则表单将发布"。我正在将表单的所有值相加,并希望将空字符串解释为 0。所以我覆盖了保存功能。

我的模型代码中的保存基本上看起来像这样,

def save(self, *args, **kwargs):
    self.cei_total = 0
    self.aggbs_total = 0
    ceis = [self.cei_0,self.cei_1,self.cei_2,self.cei_3,self.cei_4,self.cei_5,self.cei_6,self.cei_7,self.cei_8,self.cei_9,self.cei_10,self.cei_11,self.cei_12,self.cei_13,self.cei_14,self.cei_15 ]
    for c in ceis:
        if c != '':
            self.cei_total += 1
    aggbss = [self.aggbs_0, self.aggbs_1, self.aggbs_2, self.aggbs_3, self.aggbs_4, self.aggbs_5, self.aggbs_6, self.aggbs_7]
    for a in aggbss:
        if a != '':
            self.aggbs_total += a # it's a radio group, a could be 1,2,3,4 if not ''
    # And so on...
    super(Survey, self).save(*args, **kwargs)

其中 cei_0-15 是 BooleanFields 或 CharFields。aggbs_0-7 是 PositiveSmallIntegerFields。

必须有更好的方法来做到这一点。

这是执行此操作的一种方法:

self.cei_total = sum(1 for value in ceis if value)
self.aggbs_total = sum(value for value in aggbss if value)

此外,您可以使用 getattr() ,而不是定义这些ceisaggbss列表,如下所示:

ceis = (getattr(self, field) for field in self._meta.fields 
        if field.name.startswith('cei_'))
print sum(1 for value in ceis if value)

最新更新