Can Django models use MySQL functions?

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

    Here is a working solution, based in part on (http://www.djangosnippets.org/snippets/824/):

    class Employee(models.Model):
       social_security_number = models.CharField(max_length=32)
    
       def _get_ssn(self):
           cursor = connection.cursor()
           cursor.execute("SELECT AES_DECRYPT(UNHEX(social_security_number), %s) as ssn FROM tablename WHERE id=%s", [settings.SECRET_KEY, self.id])
           return cursor.fetchone()[0]
    
       def _set_ssn(self, ssn_value):
           cursor = connection.cursor()
           cursor.execute("SELECT HEX(AES_ENCRYPT(%s, %s)) as ssn", [ssn_value, settings.SECRET_KEY])
           self.social_security_number = cursor.fetchone()[0]
    
       ssn = property(_get_ssn, _set_ssn)
    

    And the results:

    >>> from foo.bar.models import Employee
    >>> p=Employee.objects.create(ssn='123-45-6789')
    >>> p.ssn
    '123-45-6789'
    
    mysql> select * from foo_employee;
    +----+----------------------------------+
    | id | social_security_number           |
    +----+----------------------------------+
    | 31 | 41DF2D946C9186BEF77DD3307B85CC8C |
    +----+----------------------------------+
    1 row in set (0.00 sec)
    

提交回复
热议问题