37

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
Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
Cerin
  • 60,957
  • 96
  • 316
  • 522

4 Answers4

37

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

Sarah Messer
  • 3,592
  • 1
  • 26
  • 43
35

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.

Afriza N. Arief
  • 7,696
  • 5
  • 47
  • 74
Spacedman
  • 92,590
  • 12
  • 140
  • 224
  • Thanks. I had been using something similar, but that snippet's far more simple. – Cerin Feb 07 '11 at 13:55
  • 4
    Thanks for the great snippet. Do you know if this supports filtering? i.e. Does `Foo.objects.filter(data=my_file)` process `my_file` through `get_data`? – Patrick Jan 03 '12 at 01:13
10

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'
Michael Waterfall
  • 20,497
  • 27
  • 111
  • 168
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • Sorry for the lack of detail, I was investigating at that point. As of Django 1.2 the [db_type](https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.db_type) method takes a `connection` argument. This was the cause of the exception during `syncdb`. I have amended the code. – Michael Waterfall Apr 25 '12 at 08:50
0

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.

B Robster
  • 40,605
  • 21
  • 89
  • 122