Django:保存模型时检测一组字段的更改
问题
我的模型中有一个字段需要一些计算。我想在保存模型时执行这些计算。但是,因为它是资源密集型的,所以我只想在某些字段发生更改时才执行这些计算。
最初的想法
将 3 个字段的哈希值保留为模型中的不同字段。保存时,对三个字段进行哈希处理,如果等于模型中当前保存的字段,则继续保存实例,无需进一步工作。否则,执行计算,保存计算结果并保存新的哈希值。
我的问题:
这是最好的选择吗?如果不是,请分享什么会更好以及为什么。
如果没有更好的方法:我应该使用哪种哈希?为什么?
我应该使用哪种 Django 模型字段类型来保存哈希?
The problem
I have a field in my model that requires some calculation. I want to perform these calculations when the model is saved. However, because it is resource intensive, I want to only perform these calculations when certain fields have changed.
Initial thought
Keep the hash of the 3 fields as a different field in the model. On save, hash the three fields and, if equal to the the one currently saved in the model, continue on saving the instance without further work. Otherwise, perform calculations, save the results of the calculation and save new hash.
My questions:
Is this the best option? If not, please share what would be better and why.
If there isn't a better way: Which kind of hash should I use? And why?
Which kind of Django model field type should I use to save the hash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我正在提交我最初想法的实现,作为其他人批评的答案:
models.py
如果有人有任何建议、评论或疑虑; 请分享!
I am submitting the implementation of my initial thought as an answer to be critiqued by others:
models.py
If anyone has any suggestions, comments or concerns; please share!
向 save 方法提供请求参数并定义此自定义保存方法:
将 admin.py 更新为如下所示:
Supply request argument to the save method and define this custom save method:
Update your admin.py to something like this:
为什么不将实例与数据库进行比较...类似:
Why not compare the instance with the db... something like: