Django管理接口在内联d之后读取了

2024-09-28 01:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文:

我刚从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)

问题:

我的应用程序的管理接口有一些账单,这些账单还包括使用admin.StackedInline内联的相关billPart对象。当我删除连接到特定账单的最后一个billpart时,billpartment的amount()属性中出现divisionbyzero错误。属性正在由billpartment的__str__()方法读取。在

从数据库中删除billpartment对象之后,它似乎正在尝试读取partment的__str__方法。但是因为它不再存在于数据库中,str(self.amount)会导致DivisionByZero错误。在

为什么管理接口要读取我刚删除的对象的__str__()方法?我应该对amount()方法进行边大小写吗?在


Tags: 对象方法selfreturnmodelsdefamountclass
1条回答
网友
1楼 · 发布于 2024-09-28 01:27:24

Why would the admin interface be trying to read the str() method of an object I've just removed? Should I edge-case the amount() method?

我的任务是因为它使用该属性来显示信息(messages包)。在

您可以尝试重写__str__,然后检查自身金额exists/返回正确,否则返回空字符串或其他可读消息。在

相关问题 更多 >

    热门问题