Django pre_save signal

戏子无情 提交于 2019-12-13 02:23:37

问题


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(' -> ', ', ')

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.


回答1:


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)
 ...

See the documentation.



来源:https://stackoverflow.com/questions/8022257/django-pre-save-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!