【发布时间】: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