【发布时间】:2012-07-12 23:56:42
【问题描述】:
class PO(models.Model)
qty = models.IntegerField(null=True)
cost = models.IntegerField(null=True)
total = qty * cost
我将如何解决上面的total = qty * cost。我知道这会导致错误,但不知道如何处理。
【问题讨论】:
class PO(models.Model)
qty = models.IntegerField(null=True)
cost = models.IntegerField(null=True)
total = qty * cost
我将如何解决上面的total = qty * cost。我知道这会导致错误,但不知道如何处理。
【问题讨论】:
您可以将total 设为property 字段,请参阅docs
class PO(models.Model)
qty = models.IntegerField(null=True)
cost = models.IntegerField(null=True)
def _get_total(self):
"Returns the total"
return self.qty * self.cost
total = property(_get_total)
【讨论】:
total 的行为就像一个字段,您可以像其他字段一样通过类对象访问它。
PO._meta.get_fields() 中也不可见。 GenericRelation 等其他计算字段将在此处列出。从django.forms.fields.Field 继承的方法将是非常可取的!
class PO(models.Model)
qty = models.IntegerField(null=True)
cost = models.IntegerField(null=True)
@property
def total(self):
return self.qty * self.cost
【讨论】:
total = property(_get_total) identical 到 @property?检查here。