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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you’re using Django >= 1.6, there’s a BinaryField
Method 2
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.
Method 3
I have been using this simple field for ‘mysql’ backend, you can modify it for other backends
class BlobField(models.Field):
description = "Blob"
def db_type(self, connection):
return 'blob'
Method 4
Also, check out Django Storages’ Database Storage:.
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0