简体   繁体   English

如何在Django管理模型中计算字段

[英]how to calculate field in django admin model

i have a model that i have added to my django admin panel 我有一个已添加到django管理面板中的模型

from django.db import models
from django.contrib import admin

class Employee(models.Model):
   fee = models.IntegerField(null=False)
   vat = models.IntegerField(null=False)

and have added this my admin panel 并将其添加到我的管理面板中

admin.site.register(Employee, EmployeeAdmin)
 readonly_fields('vat',)

so while adding a new employee, the admin inputs the fee amount, id like vat to be calculated and shown as a direct result of entering the vat. 因此,在添加新员工时,管理员输入要计算的费用金额(如增值税),并显示为输入增值税的直接结果。 how can create this calculation on the fly as the admin is entering the fee 如何在管理员输入费用时即时创建此计算

i might be completely wrong here, but couldn't you just use a property for that instead of storing vat in the database? 我在这里可能是完全错误的,但是您不能只为此使用一个属性,而不是在数据库中存储vat吗?

on your model, declare: 在模型上,声明:

@property
def vat(self):
    return calculation_of_vat(self.fee)

you can override the save method: 您可以覆盖save方法:

def save(self, *args, **kwargs):
    self.vat=self.calculate_vat(self.fee)
    super(ClassModel, self).save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM