Django Admin:检测对象字段的子集是否已更改以及其中哪些字段已更改
我需要检测管理员中某些模型的某些字段何时发生更改,以便稍后根据更改的字段以及这些字段的先前/当前值发送通知。
我尝试使用 ModelForm
并覆盖 save()
方法,但表单的 self.cleaned_data
和 seld.instance
已经有了字段的新值。
I need to detect when some of the fields of certain model have changed in the admin, to later send notifications depending on which fields changed and previous/current values of those fields.
I tried using a ModelForm
and overriding the save()
method, but the form's self.cleaned_data
and seld.instance
already have the new values of the fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
修改上面的答案...从 Dominik Szopa 获取出色的函数并更改它将解决您的关系更改检测:使用这个:
然后在您的代码中您可以说(避免尝试/除非出于性能原因):
如果您在执行此操作在“模型”级别,没有办法保存额外的查询。当您到达“保存”点时,数据已经更改。我的第一篇文章,如果我听起来像个白痴,请原谅我。
Modifying the answer above... taking the brilliant function from Dominik Szopa and changing it will solve your relationship change detection: Use this:
Then in your code you can say (avoid try/except for performance reasons):
If you are doing this at the "model" level, there is no way to save the extra query. The data has already been changed by the time you reach the "Save" point. My first post, so forgive me if I sound like an idiot.
为了避免额外的数据库查找,我修改了构造函数以记住初始值并稍后在 save 方法中使用它:
To avoid extra DB lookup, I modified constructor to remember initial value and use this in save method later:
为了获得两个模型实例的差异,您还可以使用此 功能。它与模型实例进行比较并返回更改字典。
In order to get differences of two model instances, you can also use this function. It compare to model instances and returns dictionary of changes.
您需要做的是在完全保存之前从 save 方法内的数据库中获取正在处理的对象的额外副本。例子:
What you'll need to do is get an extra copy of the object you're working on from the database inside the save method before fully saving it. Example: