Can Django models use MySQL functions?

前端 未结 6 1641
情深已故
情深已故 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:26

    It's definitely hackish, but it seems Django won't let you do it any other way at the moment. It's also worth noting that to_python will be called every time you change the value in python in addition to when it is first loaded.

    from django.db import connection, models
    import re
    
    class EncryptedField(models.TextField):
        __metaclass__ = models.SubfieldBase
    
        def to_python(self, value):
            if not re.match('^*some pattern here*$', value):
                cursor = connection.cursor()
                cursor.execute('SELECT AES_DECRYPT(%s, %s)', [value, settings.SECRET_KEY])
                return cursor.fetchone()[0]
            return value
    
        def get_db_prep_value(self, value):
            cursor = connection.cursor()
            cursor.execute('SELECT AES_ENCRYPT(%s, %s)', [value, settings.SECRET_KEY])
            return cursor.fetchone()[0]
    
    
    class Encrypt(models.Model):
        encrypted = EncryptedField(max_length = 32)
    

提交回复
热议问题