Django pre_save信号 [英] Django pre_save signal
问题描述
我需要能够在保存模型数据之前对其进行更改,因此我认为使用pre_save处理程序是最佳选择:
I needed to be able to change my model data before it's saved, so I considered using pre_save handler to be the best option:
@receiver(pre_save, weak = False)
def pre_category_save(sender, **kwargs):
if kwargs['instance'].tags is None:
kwargs['instance'].tags = kwargs['instance'].__unicode__().replace(' -> ', ', ')
在kwargs的实例键下,我希望找到要保存的实际模型实例,但是却得到了LogEntry类的对象-这就是为什么我的函数无法返回此错误的原因:'LogEntry'对象没有属性标签".所以-我该如何解决?检查实例是否具有属性标签不是解决方案,因为我总是只获得logentry对象.我最终可以重载Model.save方法,尽管我不想这样做.
Under the instance key of kwargs I expected to find the actual model instance I'm saving, but instead I got an object of LogEntry class - that's the cause why my function fails returning this error: 'LogEntry' object has no attribute 'tags'. So - how can I fix that? Checking if instance has attribute tags is not a solution, because I always get only logentry object. I can eventually overload Model.save method, though I'd rather not do this.
推荐答案
您尚未指定此信号正在接收的模型类,因此它本身已连接到 all 模型保存-包括LogEntry.相反,请执行以下操作:
You haven't specified the model class that's being received by this signal, so it's connected itself to all model saves - including LogEntry. Instead, do this:
@receiver(pre_save, sender=MyModel, weak=False)
...
请参见文档.
这篇关于Django pre_save信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!