UnicodeDecodeError:无法将unicode字符串保存到数据库

时间:2015-05-05 14:28:42

标签: django python-2.7

我有一个从xml通过lxml派生的unicode字符串:

>>> name
u'\u0414\u0438\u0434\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u0441\u0442\u043e\u043b \u0438\u0437 \u043c\u044f\u0433\u043a\u0438\u0445 \u0431\u043b\u043e\u043a\u043e\u0432.'

当我尝试将其保存为模型属性之一时,我会收到错误

product = Product(name=name, slug='er', category=c, description='wer', price=1)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 12: ordinal not in range(128)

完整追溯:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/oleshko/design/detsad-komplekt/project/catalog/tools.py", line 31, in parseCML
    product = Product(name=name, slug='er', category=c, description='wer', price=1)
  File "/home/oleshko/design/.virtualenvs/detsad-komplekt/local/lib/python2.7/site-packages/django/db/models/base.py", line 468, in __init__
    setattr(self, field.name, rel_obj)
  File "/home/oleshko/design/.virtualenvs/detsad-komplekt/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 627, in __set__
    self.field.rel.to._meta.object_name,
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 12: ordinal not in range(128)

这是我的功能:

def parseCML():
    with open('/home/oleshko/desktop/webdata/import1.xml', 'r') as xml_file:
        tree = etree.parse(xml_file)
    root = tree.getroot()
    elems = root[1][4]
    res = []
    for prod in elems:
        for cat in prod[4]:
            c = Category.objects.filter(integration_id=cat.text)       
        name = prod[2].text
        product = Product(name=name, slug='er', category=c, description='wer', price=1)

    return name

产品型号定义:

@python_2_unicode_compatible
class Product(TimeStampedModel):
    """ Product base class """
    sku = models.CharField(verbose_name='Артикул', max_length=50, blank=True, null=True)
    name = models.CharField( verbose_name='Название', max_length = 254 )
    slug = models.SlugField( max_length = 50, unique = True, help_text = 'название для URL' )
    category = models.ForeignKey(Category, verbose_name='Категория продукта', related_name='products')
    producer = models.ForeignKey(Producer, verbose_name='Бренд', related_name='producer_products', blank=True, null=True)
    description = RichTextField( verbose_name='Описание продукта', blank=True)
    collection = models.CharField(db_index=True, max_length=100, blank=True, verbose_name='Коллекция')
    price = models.DecimalField(verbose_name='Цена', max_digits=8, decimal_places=2)


    objects = InheritanceManager()

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:2)

您正在尝试将无效值设置为Product.category字段。它应该是实例,而不是查询集。尝试使用first()方法获取Category实例:

c = Category.objects.filter(integration_id=cat.text).first()
...
product = Product(name=name, slug='er', category=c, description='wer', price=1)

我怀疑当django为无效字段值构建错误消息时会发生unicode错误。