【问题标题】:Accessing the __unicode__ field of a ForeignKey in Django model在 Django 模型中访问 ForeignKey 的 __unicode__ 字段
【发布时间】: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


【解决方案1】:
return u'%s %s %s' % (self.invoice, self.amount, self.description)

unicode.__mod__() 看到“%s”并在元素上调用unicode()。

【讨论】:

  • 就是这样 - 谢谢。出于兴趣,如果我想显式调用已在类中“定义”的函数,我可以通过外键连接以某种方式调用它吗?
  • @user3074252:是的,就像你调用方法一样。
  • 我使用 django 1.6 得到: 匹配查询不存在。我已经返回 '%s' % (self.,)
猜你喜欢
  • 2014-07-19
  • 2017-12-15
  • 2016-02-14
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2018-03-01
  • 2013-03-16
  • 1970-01-01
相关资源
最近更新 更多