Django unicode 不起作用



我是Python写作的新手,我正在尝试设置我的数据库以在django管理面板中管理它。我的问题是,当我定义 unicode 时,它不起作用,我不知道为什么。

class Doors(models.Model):
door_uid = models.IntegerField(primary_key=True)
door_owner = models.IntegerField()
door_ownertype = models.IntegerField()
door_name = models.CharField(max_length=32)
  class Meta:
    verbose_name = 'Drzwi'
    verbose_name_plural = 'Drzwi'
    managed = True
    db_table = 'hrp_doors'
    def __unicode__(self):
        return self.door_uid

完成后,它仍然显示"HrpDoors 对象"。我做错了什么?

不确定为什么你会得到一个HrpDoors对象。

您可能遇到缩进问题。此外,您的 unicode 函数返回一个整数:

class HrpDoors(models.Model):
    door_uid = models.IntegerField(primary_key=True)
    ...
    class Meta:
        ...
    def __unicode__(self):
        return unicode(self.door_uid)

在您的情况下,__unicode__ 属性是一种class Meta的方法,因为它应该适用于HrpDoors

试试这个:

class HrpDoors(models.Model):
    door_uid = models.IntegerField(primary_key=True)
    door_owner = models.IntegerField()
    door_ownertype = models.IntegerField()
    door_name = models.CharField(max_length=32)
    class Meta:
        verbose_name = 'Drzwi'
        verbose_name_plural = 'Drzwi'
        managed = True
        db_table = 'hrp_doors'
    def __unicode__(self): #Look at the indentation of unicode - same level as attributes of class model
        return u'%s' % self.door_uid #Also, return unicode explicitly

以下是相关文档

最新更新