Django模型可以使用MySQL函数吗?
是否有一种方法可以在每次读取或加载模型数据时强制Django模型将字段传递给MySQL函数?为了阐明我在SQL中的含义,我希望Django模型产生类似以下内容的东西:
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 produce something like the following:
在模型加载时:从表名中选择AES_DECRYPT(字段名,密码)
On model load: SELECT AES_DECRYPT(fieldname, password) FROM tablename
在模型保存时:INSERT INTO表名VALUES(AES_ENCRYPT(用户输入,密码))
On model save: INSERT INTO tablename VALUES (AES_ENCRYPT(userinput, password))
我将定义一个自定义模型字段.覆盖to_python
方法以在加载模型时运行解密,并覆盖get_db_prep_value
以便在保存时运行加密.
I would define a custom modelfield for the column you want encrypted/decrypted. Override the to_python
method to run the decryption when the model is loaded, and get_db_prep_value
to run the encryption on saving.
请记住将字段的元类设置为models.SubfieldBase
,否则将不会调用这些方法.
Remember to set the field's metaclass to models.SubfieldBase
otherwise these methods won't be called.