Can Django models use MySQL functions?

前端 未结 6 1644
情深已故
情深已故 2021-02-06 16:05

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to

6条回答
  •  离开以前
    2021-02-06 16:43

    After deep search in the implementation of Django ORM,

    I found that it can be solved by something like this:

    class EncryptedField(models.BinaryField):
        @staticmethod
        def _pad(value):
            return value + (AES.block_size - len(value) % AES.block_size) * b('\x00')
    
        def _encrypt(self, data):
            if not data:
                return None
            return self.cipher.encrypt(self._pad(data.encode('utf8')))
    
        def _decrypt(self, data):
            if not data:
                return None
            return self.cipher.decrypt(force_bytes(data)).rstrip(b'\x00').decode('utf8')
    
        @property
        def cipher(self):
            return AES.new(KEY, mode=AES.MODE_CBC, IV=self._iv)
    
        def get_db_prep_value(self, value, connection, prepared=False):
            if value is not None:
                value = self._encrypt(value)
                if value:
                    value = binascii.hexlify(value)
            return value
    
        def get_placeholder(self, value, compiler, connection):
            return 'unhex(%s)'
    

提交回复
热议问题