Django Blob 模型字段 [英] Django Blob Model Field

查看:47
本文介绍了Django Blob 模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Django 的 ORM 和 PostgreSQL 后端存储二进制数据的blob"?是的,我知道 Django 不喜欢这种事情,是的,我知道他们更喜欢你使用 ImageField 或 FileField,但我只想说,这对我的应用程序来说是不切实际的.

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.

我尝试过使用 TextField 破解它,但是当我的二进制数据没有严格确认模型编码类型(默认情况下为 unicode)时,我偶尔会出现错误.例如

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

推荐答案

这个片段有什么好处:

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屋!

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