如何在预保存信号中查找是否插入或更新

通过利用 pre_save,我们可以确定我们数据库上的 save 操作是关于更新现有对象还是创建新对象。

为了实现这一点,你可以检查模型对象的状态:

    @receiver(pre_save, sender=User)
    def pre_save_user(sender, instance, **kwargs): 
        if not instance._state.adding:
            print ('this is an update')
        else:
            print ('this is an insert')

现在每次发生 save 动作时,pre_save 信号都会运行并打印出来:

  • this is an update 如果动作来自更新动作。
  • this is an insert 如果动作来自插入动作。

请注意,此方法不需要任何其他数据库查询。