title: How do I properly format a StringIO object(python and django) to be inserted into an database?
body: <p>I have a requeriment to store images in the database using django, and for that I created a custom field :</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I have already implemented a custom <a href="http://docs.djangoproject.com/en/1.2/howto/custom-file-storage/" rel="nofollow">storage system</a> 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. </p>
  
  <p>I have some questions about the problem:</p>
  
  <ul>
  <li>What should I return in the 'get_db_prep_value' method? </li>
  <li>If the expected value is an ASCII string, can I represent the blob(hexadecimal escapes) in a database independent way?</li>
  <li>If not, are there built in libraries that handle this kind of conversion for me?</li>
  <li>What can I expect to receive as input for the 'to_python' method, and how can I convert it to a StringIO object?</li>
  </ul>