Can Django models use MySQL functions?

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

    Instead of on model load, you can create a property on your model, and when the property is accessed, it can read the database:

    def _get_foobar(self):
        if not hasattr(self, '_foobar'):
    
            cursor = connection.cursor()
            self._foobar = cursor.execute('SELECT AES_DECRYPT(fieldname, password) FROM tablename')[0]
        return self._foobar
    foobar = property(_get_foobar)
    

    Now after loading, you can refer to mything.foobar, and the first access will retrieve the decryption from the database, holding onto it for later accesses.

    This also has the advantage that if some of your code has no use for the decryption, it won't happen.

提交回复
热议问题