Django模型@property默默地失败了

时间:2014-04-13 04:39:56

标签: django django-models

我刚刚开始捣乱@property并且我有一个似乎无声地失败而且我无法找出原因:

class Tap(models.Model):

    beer = models.CharField(max_length=20)
    ibu_actual =  models.IntegerField(default=0)
    og_actual = models.DecimalField(max_digits=4,
            decimal_places=3, default=0)
    fg_actual = models.DecimalField(max_digits=4,
            decimal_places=3, default=0)

    @property
    def calories(self):
        if (self.og_actual == 1 and self.fg_actual == 1):
            print "0 kCal"
            return 0
        else:
            calories_from_alcohol = (1881.22 * (self.fg_actual * (self.og_actual self.fg_actual)))
            calories_from_carbs = 3550 * self.fg_actual * ((0.1808 * self.og_actual) + (0.8192 * self.fg_actual) - 1.0004)
            print "%d kCal" % (calories_from_alcohol + calories_from_carbs)
            return calories_from_alcohol + calories_from_carbs

在我的模板中,卡路里只返回一个空白,当在'runserver'下运行时,我的打印字符串永远不会出现。我补充道     TEMPLATE_STRING_IF_INVALID =“无效字符串'%s'” 到我的设置,它显示没有生成任何模板显示。 例如,如果我愚蠢地计算,将每个设置为1,那么它就可以工作。 所以我猜数学是因为某些原因而失败的?一个不同的财产确实有效:

@property
def bugu(self):
#BU:GU is (ibu/((og-1)*1000)) if og > 1
    if self.og_actual > 1:
        print "bugu"
        return (self.ibu_actual/((self.og_actual-1)*1000))
    else:
        return 0

我的数学在shell中工作:

(InteractiveConsole)
>>> fg = 1.011
>>> og = 1.051
>>> fg + og
2.062
>>> (1881.22 * (fg * (og -fg)))
76.07653680000006
>>> 3550 * fg * ((0.1808 * og) + (0.8192 * fg) - 1.0004)
63.99993959999945
>>>

我无论如何都不是蟒蛇高手,所以我很难过!

感谢。

更新: 我添加了几个调试打印语句,正在输入函数:

Starting development server at http://192.168.0.15:7000/
Quit the server with CONTROL-C.
bugu
starting calories
calculating calories from carbs
bugu
starting calories
calculating calories from carbs
bugu
starting calories
calculating calories from carbs
[13/Apr/2014 05:26:30] "GET / HTTP/1.1" 200 7530

我尝试交换酒精和碳水化合物计算的顺序,但它似乎没有区别,它停在任何一个。

1 个答案:

答案 0 :(得分:0)

我回到Django shell并在那里查询我的对象并收到错误:

TypeError: unsupported operand type(s) for *: 'float' and 'Decimal' 

以及我的问题的答案:https://github.com/plomino/Plomino/issues/308

所以我将我的Decimal字段转换为浮点数,现在它可以工作了。我会把它留给子孙后代,希望有一天能帮助别人。