Django Blob模型字段 [英] Django Blob Model Field
问题描述
如何使用Django的ORM与PostgreSQL后端存储二进制数据的blob?是的,我知道Django对这种事情皱起眉头,是的,我知道他们更喜欢使用ImageField或FileField,但是足够的话说,这对我的应用来说是不切实际的。
我尝试使用TextField进行黑客攻击,但是当我的二进制数据没有严格确认模型编码类型时,我遇到偶然的错误,默认情况下是unicode。例如
psycopg2.DataError:编码UTF8的无效字节序列:0xe22665
/ pre>
解决方案这个代码段有什么好处:
http://djangosnippets.org/snippets/1597/
这可能是将二进制数据存储在
TextField中的最简单的解决方案。
import base64
from django.db import models
class Foo(models.Model):
_data = models.TextField
db_column ='data',
blank = True)
def set_data(self,data):
self._data = base64.encodestring(data)
def get_data(self):
return base64.decodestring(self._data)
data = property(get_data,set_data)
有一些其他片段可能有帮助。 p>
How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? Yes, I know Django frowns upon that sort of thing, and yes, I know they prefer you use the ImageField or FileField for that, but suffice it to say, that's impractical for my application.
I've tried hacking it by using a TextField, but I get occassional errors when my binary data doesn't strictly confirm to the models encoding type, which is unicode by default. e.g.
psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0xe22665
解决方案This snippet any good:
http://djangosnippets.org/snippets/1597/
This is possibly the simplest solution for storing binary data in a TextField.
import base64 from django.db import models class Foo(models.Model): _data = models.TextField( db_column='data', blank=True) def set_data(self, data): self._data = base64.encodestring(data) def get_data(self): return base64.decodestring(self._data) data = property(get_data, set_data)
There's a couple of other snippets there that might help.
这篇关于Django Blob模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!