从其他字段计算的 Django 模型字段

Django Model field calculated from other fields

这里还有很多其他问题,但 none 其中有帮助。

我想要 yield 字段由 yield = starts / finishes 字段计算。我想用 Highcharts 绘制它。

但是,当我通过管理门户添加对象时 - 它正在设置 yield = 0 并且不会计算。

models.py:

class wYield(models.Model):
    starts = models.PositiveIntegerField(default=0)
    finishes = models.PositiveIntegerField(default=0)


## ONE: i've tried the below:
    yield_num = model.FloatField()
    def save(self, *args, **kwargs):
        if self.starts > 0:
             self.yield = self.finishes / self.starts 
        else:
             self.yield = 0
        super(wYield, self).save(*args, **kwargs)

## TWO: i've tried this but then I don't know how to see it in the Admin view:
    def _set_yield(self):
        if self.starts > 0:
             x = self.finishes / self.starts 
        else:
             x = 0
        return x
    yield_num = property(_set_yield)

 ## THREE: I think this works the same as TWO
    @property
    def yield_num(self):
        if self.starts > 0:
             return self.finishes / self.starts
        else:
             return 0

admin.py:

from .models import wYield

class wYieldAdmin(admin.ModelAdmin):
    list_display = ('starts', 'finishes', 'yield_num')

admin.site.register(wYield, wYieldAdmin)

也许您不必每次都将其保存在数据库中,因为它可以即时计算;否则你会浪费 space。更不用说 db 值中的口是心非了。

此外,如果明天您的 yield 逻辑发生变化,您将可以完全自由地对 lambda 表达式进行更改。这是一个例子:

Class wYieldAdmin(admin.ModelAdmin):
    yield = lambda self: (self.finishes / self.starts) if self.starts > 0 else 0
    yield.short_description = 'Yield'
    list_display = ('starts', 'finishes', 'yield')

弄明白了(在 AbhiP 的帮助下!)Python int 类型转换是罪魁祸首。愚蠢的问题!

下面是有效的方法,允许我不保存计算字段(但显示它并使它像模型中的字段一样):

@property
def yield_num(self):
    if self.starts > 0:
        #needed the float() to cast it out of an int
        return self.finishes / float(self.starts)
    else:
        return 0
Class wYieldAdmin(admin.ModelAdmin):
yield = lambda self: (self.finishes / self.starts) if self.starts > 0 else 0
yield.short_description = 'You have a big head'
list_display = ('starts', 'finishes', 'yield')