将os.urandom变量存储到Django中的Sqlite数据库中 [英] Store os.urandom variable to Sqlite database in Django

查看:89
本文介绍了将os.urandom变量存储到Django中的Sqlite数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将随机变量存储到Django中的Sqlite数据库中,但出现此错误:

I'm trying to store random variable to Sqlite database in Django, but I get this error:


您不得使用8位字节串,除非您使用可以解释8位字节串的text_factory(例如text_factory = str)。强烈建议您改为将应用程序切换为Unicode字符串。

You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

这是我的代码:

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)

我使用Python 2.7.10和Django 1.9。

I use Python 2.7.10 and Django 1.9.

推荐答案

如果仍然可行,您可以更改模型以使用 BinaryField

If still possible, you could alter your model to use BinaryField:

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

如果另一方面,该模型已经定型,请考虑一些二进制到文本编码,例如base64 :

If on the other hand the model is already set in stone, consider some binary to text encoding, like base64:

from base64 import b64encode

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

这篇关于将os.urandom变量存储到Django中的Sqlite数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆