上下文:
我刚从Django开始。为了熟悉它,我正在编写一个网络应用程序来跟踪家庭账单。每一张钞票都有与欠钱的每个人相关的账单部分。欠款额按账单总额除以部分总数(即所涉人数)计算。见下文:
class Bill(models.Model):
description = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=9, decimal_places=2)
paid_by = models.ForeignKey(Person)
def __str__(self):
return self.description
class BillPortion(models.Model):
bill = models.ForeignKey(Bill, related_name='portions')
person = models.ForeignKey(Person, related_name='bill_portions')
@property
def amount(self):
return self.bill.amount / self.bill.portions.count()
def __str__(self):
return str(self.person) + ' owes ' + str(self.bill.paid_by) + \
' $' + str(self.amount) + ' for ' + str(self.bill)
发行:
我的应用程序的管理界面也包含了使用BillPortion内联使用admin.StackedInline
的相关的admin.StackedInline
对象。当我删除连接到特定票据的最后一个BillPortion时,在BillPortion的amount()
属性中会出现一个DivisonByZero错误。该属性正在由BillPortion的__str__()
方法读取。
看起来,在从数据库中删除BillPortion对象之后,它将尝试读取该部分的__str__
方法。但是,因为它不再存在于数据库中,所以str(self.amount)
会导致DivisionByZero错误。
为什么管理界面要尝试读取我刚刚删除的对象的__str__()
方法?我是否应该用amount()
方法进行边缘处理?
发布于 2014-12-30 01:26:17
为什么管理界面要尝试读取我刚刚删除的对象的str()方法?我是否应该用数值()方法来加边?
我的请求是因为它使用该属性来显示信息(消息包)。
您可以尝试重写__str__
,然后检查self.amount是否存在/返回正确,如果不正确,则返回空字符串或其他可读的消息。
https://stackoverflow.com/questions/27698202
复制相似问题