【问题标题】:Is it posible to get a model's unicode from another model?是否可以从另一个模型获取模型的 unicode?
【发布时间】:2014-10-24 11:24:06
【问题描述】:

我有两个表,HousingPhoto(一对多关系)。 住房表根据类型和交易字段返回 unicode。我希望Photo unicode 成为Housing 的 unicode + 它自己的主键。这可能吗?

class Housing(models.Model):
    type = models.CharField(max_length=16)
    transaction = models.CharField(max_length=16)


    def __unicode__(self):
        if self.type.lower() == "house" and self.transaction.lower() == "sell":
            return "HS" + str(self.pk+100)
        elif self.type.lower() == "house" and self.transaction.lower() == "rent":
            return "HR" + str(self.pk+100)
        elif self.type.lower() == "apt" and self.transaction.lower() == "sell":
            return "AS" + str(self.pk+100)
        elif self.type.lower() == "apt" and self.transaction.lower() == "rent":
            return "AR" + str(self.pk+100)
        else:
            return "ERROR" + str(self.pk+100)

class Photos(models.Model):
    housing= models.ForeignKey(Housing)
    photo_url = models.ImageField(upload_to="photos/", blank=True, null=True)

    def __unicode__(self):
        return "Img " + str(self.pk)

【问题讨论】:

  • 顺便说一句,您应该避免将复杂的逻辑放在__unicode__ 方法中。最好把它放在一个单独的方法中,然后从__unicode__ 调用它。
  • 谢谢,有什么原因吗?

标签: python django unicode models


【解决方案1】:

您可以简单地引用相关的self.housing对象属性,或者将其转换为Unicode:

def __unicode__(self):
    return u"Img({!r}, {})".format(self.pk, self.housing)

这会将self.housing.__unicode__() 的输出放入主键之后生成的Unicode 字符串中。这是可行的,因为自动插入带有unicode.format()unicode 字符串对象将使用unicode(self.housing)

您的Housing.__unicode__() 方法可以稍微简化:

def __unicode__(self):
    if (self.type.lower() not in ('house', 'apt') or
           self.transaction.lower() not in ('sell', 'rent'):
        return 'ERROR{}'.format(self.pk + 100)
    type_, transaction = self.type[0].upper(), self.transaction[0].upper()
    return '{}{}{}'.format(type_, transaction, self.pk + 100)

请注意,这会触发对self.housing 关系的单独查询;如果您要显示大量 Photos 实例,您很容易会在每个显示的 Photos 实例中产生一个额外的数据库查询,从而降低您的应用程序的速度。

【讨论】:

  • 感谢@Martin Pieters。我试过这个,但无法让它工作。不过,我找到了一种解决方法,使用模型的主键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 2018-10-29
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多