【问题标题】:Django error Coercing to Unicode: need string or bufferDjango 错误强制转换为 Unicode:需要字符串或缓冲区
【发布时间】:2018-05-07 07:50:25
【问题描述】:

我收到此错误:

>>> Child.objects.all()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Child.objects.all()
    u = six.text_type(self)
TypeError: coercing to Unicode: need string or buffer, Main found

每当我尝试从 Child 拉出一个对象时。我尝试使用 unicode,但它仍然给我这个错误。我还评论了 **def str ** 认为这是一个问题。 我不知道我能做些什么?请帮忙

class Main(models.Model):
    website = models.CharField(db_column='Website', unique=True, max_length=250)
    main = models.CharField(db_column='Main', unique=True, max_length=100)
    tablename = models.CharField(db_column='TableName', unique=True, max_length=100)
    created_at = models.DateTimeField(db_column='Created_at')

    class Meta:
        managed = False
        db_table = 'Main'

    # def __str__(self):
    #     return self.main

    def __unicode__(self):
        return unicode(self.main)


class Child(models.Model):
    mainid = models.ForeignKey(Main, models.DO_NOTHING, db_column='MainID')
    day = models.IntegerField(db_column='Day')
    hour = models.TimeField(db_column='HOUR')
    created_at = models.DateTimeField(db_column='Created_at')

    class Meta:
        managed = False
        db_table = 'Child'

    # def __str__(self):
    #     return self.mainid

    def __unicode__(self):
        return unicode(self.mainid)

谢谢

【问题讨论】:

  • 哪个python版本。 Python 3 默认是 unicode,那你为什么要把模型强制转换成 unicode?​​span>
  • 我正在使用 Python 2
  • 真的,为什么不用python3呢?无论如何..把它放在你脚本的顶部# -*- coding: utf8 -*-
  • 我在每个文件的顶部都有这个
  • 那么你的类中不应该再有 unicode 方法了。

标签: django python-2.7


【解决方案1】:

问题是您将主对象传递给 unicode 函数。它需要一个缓冲区字符串,但你给它一个对象。

尝试更改 Child 中的 __unicode_ 方法。 (有几种方法可行)

class Child(models.Model): 
    ...
    ...
    ..

    def __unicode__(self):
        return self.mainid.__unicode__()

或者这也应该通过在 Main 对象上隐式调用 unicode 方法来工作。

     def __unicode__(self):
            return self.mainid

或者这个

     def __unicode__(self):
            return self.mainid.main

不是,Python 3 使用 __str__ 方法,而 Python 2 使用 __unicode__

【讨论】:

  • 我已经尝试了所有...我也尝试了这个: def __unicode__(self): return '%mainid' % {'mainid': self.mainid} 它仍然给我那个错误跨度>
  • 我确实从他们两个中删除了 def _str_
  • 如果您使用的是第三个最明确的版本,那么它应该给出不同的错误,因为该错误没有意义。
  • ki 明白了……它不再给我错误了……它从 Main 中给出了 main 列……当我刷新页面时……它打印出来了…… .但是在shell中......它仍然给我那个错误
  • 我刚刚发现如果您更改模型中的某些内容...您已重新加载外壳以使其生效...现在才发现 :))) 谢谢
猜你喜欢
  • 2014-02-22
  • 2011-10-04
  • 2011-05-13
  • 2012-04-12
  • 2011-07-17
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2012-06-06
相关资源
最近更新 更多