如何__repr__从数据库模型中键入unicode

问题描述 投票:2回答:1

在Win 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)
python database python-2.7 unicode flask-sqlalchemy
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)
© www.soinside.com 2019 - 2024. All rights reserved.