【发布时间】:2013-12-12 18:16:54
【问题描述】:
我在模型的 __unicode__ 中构造了一个有用的组合字符串来识别 Django 中的单个记录。
然后我有另一个模型将第一个模型称为外键。
对于我的第二个模型,我想使用 ForeignKey 引用的第一个模型中的 __unicode__ 字符串为第二个模型构造 __unicode__ 字符串。
class Invoice(models.Model):
supplier = models.ForeignKey(Supplier)
amount = models.DecimalField("invoice total", max_digits=10, decimal_places=2)
invoice_date = models.DateField("invoice date")
def __unicode__(self): # I want to reuse this string in class Charge
return " ".join((
unicode(self.supplier),
self.invoice_date.strftime("%Y-%m-%d"),
u"£",
unicode(self.amount)
))
class Charge(models.Model):
invoice = models.ForeignKey(Invoice)
amount = models.DecimalField("amount charged to house", max_digits=10, decimal_places=2)
description = models.CharField("item description", max_length=200, null=True, blank=True)
def __unicode__(self):
return " ".join((
self.invoice.__unicode__, #How do I do this?
unicode(self.amount),
self.description,
))
第二个模型的 unicode 需要第一个模型的 unicode,而无需再次构造它。
我如何引用它?我以为我只是将发票放在我的 __unicode__ 中,它会引用索引的 unicode 字符串,但当然它会获取发票的整个实例。
【问题讨论】:
-
只需执行
self.invoice`__unicode__` 将为您评估。 -
这就是我所希望的,但我收到一个错误,提示预期字符串或 unicode,已找到发票
标签: django unicode foreign-keys admin