在Django的模型中需要一个计算值

时间:2017-10-27 06:56:10

标签: python django

我想在models.py中计算一个值。以下是文件models.py。我设法按预期获得price,但price并未显示为字段之一。我的意思是,当我输入delivery_pricesupport_price时,应计算price字段并显示在下面的页面中(附图)。这可能还是我弄错了?

delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)
support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)

#def get_price(self):
#    "Returns the price."
#    return (self.delivery_price + self.support_price)
#price = property(get_price)

price = models.DecimalField(max_digits=10, decimal_places=0,editable=False)

def save(self, *args, **kwargs):
    self.price = self.delivery_price + self.support_price
    super(Product, self).save(*args, **kwargs)

enter image description here

1 个答案:

答案 0 :(得分:2)

editable = False表示该字段不会显示在Django admin中。而是在您的admin.py ModelAdmin中,将其设为只读字段。

class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    readonly_fields = ('price',)

admin.site.register(MyModel, MyModelAdmin)