简体   繁体   English

Django Blob模型领域

[英]Django Blob Model Field

How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? 如何使用Django的ORM和PostgreSQL后端存储二进制数据的“blob”? 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. 是的,我知道Django对这种事情感到皱眉,是的,我知道他们更喜欢你使用ImageField或FileField,但这足以说明,这对我的应用来说是不切实际的。

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. 我已经尝试使用TextField进行黑客攻击,但是当我的二进制数据没有严格确认模型编码类型(默认情况下为unicode)时,我会遇到偶然的错误。 eg 例如

psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0xe22665

This snippet any good: 这个片段有什么好处:

http://djangosnippets.org/snippets/1597/ http://djangosnippets.org/snippets/1597/

This is possibly the simplest solution for storing binary data in a TextField. 这可能是在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> = 1.6,那就是BinaryField

I have been using this simple field for 'mysql' backend, you can modify it for other backends 我一直在使用这个简单的字段用于'mysql'后端,你可以为其他后端修改它

class BlobField(models.Field):
    description = "Blob"
    def db_type(self, connection):
        return 'blob'

Also, check out Django Storages' Database Storage: . 另外,查看Django Storages的数据库存储:

I haven't used it yet, but it looks awesome and I'm going to start using it as soon as I Post My Answer. 我还没有使用它,但它看起来很棒,我会在发布我的答案后立即开始使用它。

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

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