简体   繁体   English

将os.urandom变量存储到Django中的Sqlite数据库中

[英]Store os.urandom variable to Sqlite database in Django

I'm trying to store random variable to Sqlite database in Django, but I get this error: 我正在尝试将随机变量存储到Django中的Sqlite数据库中,但出现此错误:

You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). 除非使用可以解释8位字节串的text_factory(如text_factory = str),否则不得使用8位字节串。 It is highly recommended that you instead just switch your application to Unicode strings. 强烈建议您改为将应用程序切换为Unicode字符串。

Here is my code: 这是我的代码:

random_number = os.urandom(16)
SomeModel.objects.filter(id=2).update(number=random_number)

Models.py: Models.py:

class SomeModel(models.Model):
    random = models.CharField(max_length=32)

I use Python 2.7.10 and Django 1.9. 我使用Python 2.7.10和Django 1.9。

If still possible, you could alter your model to use BinaryField : 如果仍然可能,您可以更改模型以使用BinaryField

class SomeModel(models.Model):
    random = models.BinaryField(max_length=32)

If on the other hand the model is already set in stone, consider some binary to text encoding, like base64: 另一方面,如果模型已经确定,则考虑一些二进制到文本的编码,例如base64:

from base64 import b64encode

random_number = os.urandom(16)
SomeModel.objects.filter(id=2).update(number=b64encode(random_number))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM