I am trying to simulate a MySQL field VARBINARYin Django v1.1.1. The binary field stores the hexadecimal representation of the data (i.e. Used INSERT INTO test(bin_val) VALUES X'4D7953514C')
Reading Django documentation [1] I came up with this solution:
class MyTest(models.Model):
bin_val = BinValField()
class BinValField(models.Field):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
""" DB -> Python """
return ''.join('%X%X' % ((ord(byte)>>4) & 0xF, ord(byte) & 0xF) for byte in value)
def get_db_prep_value(self, value):
""" Python -> DB """
return a2b_hex(value).decode('latin1')
However, this does not work correctly because:
- Django performs Unicode conversion of binary data from MySQL
- When saving a new object, MyTest
get_db_prep_value()is called twice (I think this is a bug in Django?)
The question is, how would you model such a field?
PS: In connection with this problem is this ticket [2], which is still open after 3 years :(
[1] Django: Writing Custom Model Fields
[2] http://code.djangoproject.com/ticket/2417