如何从数据库模型获取__repr__类型的unicode
我在Windows 7上使用Python 2.7.4和flask-sqlalchemy。
在我的数据库中,有一个模型叫做šaš šuđa
,我想知道如何在这个模型中用__repr__
来显示它的名字。
class Car(db.Model):
__tablename__ = 'cars'
id = db.Column(db.Integer, primary_key=True)
county = db.Column(db.String(64))
model = db.Column(db.UnicodeText(64))
def __repr__(self):
return 'Country: %s Model: %s' % (self.country, self.model)
我尝试过用u"{0}".format(self.model)
,结果还是一样。
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0111' in position 105: ordinal not in range(128)
1 个回答
3
在Python 2中,__repr__
必须 返回一个字节串;如果你不这样做,Python会试着帮你编码。
你可以明确地对你的值进行编码:
def __repr__(self):
return 'Country: %s Model: %s' % (
self.country.encode('utf8'), self.model.encode('utf8'))
如果你想在使用Jinja2的时候返回unicode值,可以定义一个 __unicode__
方法:
def __unicode__(self):
return u'Country: %s Model: %s' % (self.country, self.model)