Django Model __unicode__记录时引发异常 [英] Django Model __unicode__ raising exception when logging
问题描述
我有一个模型类,如下所示:
I have a model class that looks like the following:
class Address(models.Model):
# taking length of address/city fields from existing UserProfile model
address_1 = models.CharField(max_length=128,
blank=False,
null=False)
address_2 = models.CharField(max_length=128,
blank=True,
null=True)
address_3 = models.CharField(max_length=128,
blank=True,
null=True)
unit = models.CharField(max_length=10,
blank=True,
null=True)
city = models.CharField(max_length=128,
blank=False,
null=False)
state_or_province = models.ForeignKey(StateOrProvince)
postal_code = models.CharField(max_length=20,
blank=False,
null=False)
phone = models.CharField(max_length=20,
blank=True,
null=True)
is_deleted = models.BooleanField(default=False,
null=False)
def __unicode__(self):
return u"{}, {} {}, {}".format(
self.city, self.state_or_province.postal_abbrev, self.postal_code, self.address_1)
键是__unicode__
方法.我有一个具有此表的外键字段的客户模型,并且正在执行以下日志记录:
The key being the __unicode__
method. I have a customer model that has a foreign key field to this table, and I am doing the following logging:
log.debug(u'Generated customer [{}]'.format(vars(customer)))
这很好,但是如果address_1字段值包含非ASCII值,请说
This works fine, but if an address_1 field value contains a non ascii value, say
57562VånNess Hwy
57562 Vån Ness Hwy
系统抛出以下异常:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 345: ordinal not in range(128)
我在django/db/models/base.py中找到了一个奇怪的方法:
I tracked this down to a strange method in django/db/models/base.py:
def __repr__(self):
try:
u = six.text_type(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str('<%s: %s>' % (self.__class__.__name__, u))
如您所见,
该方法被调用为force_str,该方法未正确处理.这是一个错误吗?如果在我的对象上调用了unicode,不是所有内容都应该在unicode中吗?
as you can see, this method is getting called to force_str, which doesn't get handled correctly. is this a bug? if unicode is getting called on my object, shouldn't everything be in unicode?
推荐答案
According to the docs, when a python object is passed as an argument to '{}'.format(obj)
,
通常的约定是,[{}内的空格式字符串(")会产生 就像您在值上调用str()一样.
A general convention is that an empty format string ("") [within the "{}"] produces the same result as if you had called str() on the value.
这意味着您正在有效地调用str(vars(customer))
,并且vars(customer)
返回一个dict
.
This means you're effectively calling str(vars(customer))
, and vars(customer)
returns a dict
.
在dict
上调用str()
会在其键和值上调用repr()
,因为否则您将获得模棱两可的输出(例如str(1) == str('1') == '1'
但repr(1) == '1' and repr('1') == '"1"'
(请参阅Python中__str__和__repr__之间的区别)
Calling str()
on a dict
will call repr()
on its keys and values because otherwise you'd get ambiguous output (eg str(1) == str('1') == '1'
but repr(1) == '1' and repr('1') == '"1"'
(see Difference between __str__ and __repr__ in Python)
因此repr()
仍在您的Address
上被调用,这将返回一个字符串.
Therefore repr()
is still being called on your Address
, which returns a string.
现在在Python 2中不允许从repr()
返回unicode- https://stackoverflow.com/a/3627835/648176 ,因此您需要在模型中覆盖__str__()
,以使其能够处理解码为ascii(
Now returning unicode from repr()
is not allowed in Python 2 - https://stackoverflow.com/a/3627835/648176, so you'll need to either override __str__()
in your model to make it handle decoding into ascii (Django docs), or do something like:
string_dict = {str(k): str(v) for (k, v) in vars(customer).items()}
log.debug(u'Generated customer [{}]'.format(string_dict))
这篇关于Django Model __unicode__记录时引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!