请参阅django休息框架中post_save中的对象更改 [英] See object changes in post_save in django rest framework
问题描述
泛型的 post_save
来处理。 RetrieveUpdateDestroyAPIView
。 我的第一个想法是使用 pre_save
来检查,但似乎 pre_save
的对象参数已经对其进行了更改。
对于django休息框架版本2.3.12的旧答案:
要检查更新时是否有更改,您必须比较未更改的模型实例是具有改变的模型实例的self.object,它是serializer.object。
传递给pre_save方法的对象参数是serializer.object,它不是但是在数据库中保存了新的更改。
未更改的模型实例是使用self.get_object_o从数据库中获取的self.object r_none()。将它与pre_save方法中的obj参数进行比较。
def pre_save(self,obj):
changed_instance = self .object
changed_instance = obj
.....#比较代码
对于django休息框架的新回答3.3:
pre_save和post_save不再有效
http://www.django-rest-framework.org/topics/3.0-announcement/#generic-视图
现在,您可以在perform_update方法中放置任何预保存或保存逻辑。例如:
def perform_update(self,serializer):
old_obj = self.get_object()
new_data_dict = serializer.validated_data
#预保存逻辑
如果old_obj.name!= new_data_dict ['name']
do_smething
.....
serializer.save ()
#保存逻辑
......
I am curious if there is a way to see what has changed on an object after saving it using the Django Rest Framework. I have some special behavior I need to check if a field has been changed from its original value that I was hoping to handle using the post_save
on generics.RetrieveUpdateDestroyAPIView
.
My first thought was to check using pre_save
but it seems that pre_save
's object argument already has the changes applied to it.
OLD ANSWER for django rest framework version 2.3.12:
To check if anything has changed on update, you will have to compare the unchanged model instance which is self.object with the changed model instance which is serializer.object.
The object argument which is passed to the pre_save method is the serializer.object which is not yet saved in the database with the new changes.
The unchanged model instance is the self.object which has been fetched from the database using self.get_object_or_none(). Compare it with the obj argument in the pre_save method.
def pre_save(self,obj):
unchanged_instance = self.object
changed_instance = obj
..... # comparison code
NEW ANSWER for django rest framework 3.3:
pre_save and post_save are no longer valid http://www.django-rest-framework.org/topics/3.0-announcement/#generic-views
Now you can place any pre save or post save logic in perform_update method. For example:
def perform_update(self, serializer):
old_obj = self.get_object()
new_data_dict = serializer.validated_data
# pre save logic
if old_obj.name != new_data_dict['name']
do_smething
.....
serializer.save()
# post save logic
......
这篇关于请参阅django休息框架中post_save中的对象更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!