2014-05-23 88 views
2

类型的Unicode使用Python 2.7.4和烧瓶SQLAlchemy的在Win 7如何__repr__从数据库模型

工作在我的数据库我有一个名为š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) 

回答

3

__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) 
+0

这是我现在得到:UnicodeDecodeError错误:'ascii'编码解码器无法解码位置53中的字节0xc5:序号不在范围内(128) –

+0

@Ecce_Homo:您是否将'__repr__'输出与其他Unicode字符串混合在其他地方? –

+0

是的,我正在使用jinja2模板语言进行循环,并以| safe来显示每个国家和模型。 –

相关问题