当我从Django将数据存储到MySQL时,出现错误:
Django Version: 1.7.7
Exception Type: Warning
Exception Value:
Invalid utf8 character string: '800363'
Exception Location: /home/virtualenv/examenv/lib/python3.4/site-packages/MySQLdb/cursors.py in _warning_check, line 127
Python Executable: /home/virtualenv/examenv/bin/python3
Python Version: 3.4.4
模型
class Test(models.Model):
"""
The model of the test
"""
# The name of the test
name = models.CharField(max_length=500)
# The description of test
description = models.TextField(blank=True)
# The test
test = models.BinaryField(blank=True)
# The author of the test
author = models.ForeignKey(settings.AUTH_USER_MODEL)
# The category of the test
category = models.ForeignKey(Category)
# date and time of create test
date_and_time = models.DateTimeField(default=timezone.now())
# How many users complete this test.
rating = models.IntegerField(default=0)
# Public or not public test
is_public = models.BooleanField(default=True)
def __str__(self):
return self.name
我已经用utf-8格式创建了数据库 如何解决此错误?
答案 0 :(得分:0)
如果没有堆栈跟踪或产生错误的行,这是一个盲目猜测。但是,我确实在模型中看到了BinaryField。我想你正在使用Python MySql Connector。
我通过将二进制数据编码为十六进制字节串来解决了同样的错误。我实际上不希望这解决任何问题,二进制是二进制的,但这就是我使用它的方式:
import binascii
bin_data = some_function()
repr(bin_data)
>>> b"R\x89\x9e\x86\xc6" # or something like that
test = Test()
# ...
hex_bin_data = binascii.hexlify(bin_data)
test.test = hex_bin_data
test.save()
hex_bin_data
输出也是bytes
。这是让我烦恼的事情。是什么让Python区分bin_data
和hex_bin_data
?应该有相同的字节没有?