Django: How to model a VBBINARY HEX MySQL field?

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

+3
3

, Django .

, :

  • utf8 utf8_bin
  • VARCHAR VARBINARY MySQL
  • to_python return hexlify(value)
+1

, .

, , CharField?

bin, .CharField hex to_python.

: - Django

0

MySQL does not store the hexadecimal representation for VARBINARY fields and does not require it in the INSERT statement. The only difference from VARCHAR is that MySQL uses binary sorting for it. You can pass any 8-bit string as a parameter to it.

0
source

Source: https://habr.com/ru/post/1720439/


All Articles