这是我的模型课:
class House(models.Model):
land_price_per_meter = models.PositiveIntegerField(default=0)
land_area = models.PositiveIntegerField(default=0)
land_price = models.PositiveIntegerField(default=0)
build_price_per_meter = models.PositiveIntegerField(default=0)
build_area = models.PositiveIntegerField(default=0)
build_price = models.PositiveIntegerField(default=0)
total_price = models.PositiveIntegerField(default=0)
这些字段是read_only:
land_price
build_price
total_price
我希望Django以如下方式(实时)计算admin change_form中的read_only字段本身:
land_price
=land_price_per_meter
*land_area
build_price
=build_price_per_meter
*build_area
total_price
=build_price
+land_price
答案 0 :(得分:0)
您可以在以下位置创建函数 admin.py
class HouseAdmin(admin.ModelAdmin):
readonly_fields = ("calc_land_price",)
def calc_land_price(self, instance):
return land_price_per_meter * land_area
calc_land_price.short_description = "land_price"
但是更好的解决方案是,如果land_price只是两个字段的乘积,则直接在模型@property中创建,然后删除land_price。 models.py
class House(models.Model):
[...]
@property
def land_price(self):
return land_price_per_meter * land_area