I have a requeriment to store images in the database using django, and for that I created a custom field :
from django.db import models
class BlobField(models.Field):
    __metaclass__ = models.SubfieldBase
    def db_type(self, connection):
        #TODO handle other db engines
        backend = connection.settings_dict['ENGINE']
        if backend == 'django.db.backends.postgresql':
            return 'bytea'
        elif backend == 'django.db.backends.sqlite3':
            return 'blob'
        else:
            raise Exception('unsuported db')
    def to_python(self, value):
        #TODO
        return value
    def get_db_prep_value(self, value, connection, prepared=False):
        #TODO              
        return value
I have already implemented a custom storage system to handle the storage/retrieval of images using a custom Model(that contains the above BlobField). The 'value' parameter in the 'get_db_prep_value' method is a 'StringIO' object that contains the image binary data. The catch is that I don't know what to return in the 'get_db_prep_value' method since the 'StringIO' object will surely contain non-printable characters.
I have some questions about the problem:
There is no constraint requiring get_db_prep_value to return "printable" characters, or ASCII ones, or otherwise-constrained sets of characters: return any byte string that catches your fancy. You'll get a string in to_python and can make a file-like StringIO instance reading its data with the_instance = StringIO.StringIO(value) (of course you'll need to import StringIO at the top of your module).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With