Python Django Blob 模型字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4915397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:08:02  来源:igfitidea点击:

Django Blob Model Field

pythondjangodjango-modelsdjango-ormdjango-blob

提问by Cerin

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.

如何使用 Django 的 ORM 和 PostgreSQL 后端存储二进制数据的“blob”?是的,我知道 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. e.g.

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

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

采纳答案by Spacedman

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.

还有一些其他片段可能会有所帮助。

回答by Anurag Uniyal

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'

回答by Ben Roberts

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.

我还没有使用它,但它看起来很棒,我将在发布我的答案后立即开始使用它。

回答by Sarah Messer

If you're using Django >= 1.6, there's a BinaryField

如果您使用的是 Django >= 1.6,则有一个BinaryField