简体   繁体   English

Django pre_save 信号:检查实例是否创建未更新,kwargs['created'](仍然)是否存在?

[英]Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist?

I am using Django's pre_save signal to implement auto_now_add.我正在使用 Django 的 pre_save 信号来实现 auto_now_add。 There is a lot of discussion on the internet on why you should or shouldn't implement it yourself.互联网上有很多关于为什么应该或不应该自己实施它的讨论。 I do not appreciate comments on this.我不欣赏对此的评论。 Neither on whether I should be rewriting the save function (I have a lot of models that use auto_now_add so using signals makes sense).无论是我是否应该重写保存功能(我有很多使用 auto_now_add 的模型,所以使用信号是有意义的)。

My question is:我的问题是:
I would like to check if the instance is created or updated.我想检查实例是否已创建或更新。 According to some sources on the internet this can be done by testing if kwargs['created'] is True.根据互联网上的一些消息来源,这可以通过测试kwargs['created']是否为真来完成。 However 'created' does not appear in my kwargs even though the instance is newly created.但是,即使实例是新创建的, 'created'也不会出现在我的kwargs中。 I was just wondering if it has ever existed or that it has disappeared magically.我只是想知道它是否曾经存在过或者它神奇地消失了。 I know I could also test if kwargs['instance'].id is set (this in fact works for me), but I'd like to know if kwargs['created'] still exists.我知道我也可以测试是否设置了kwargs['instance'].id (这实际上对我有用),但我想知道 kwargs['created'] 是否仍然存在。

Primary key attribute usually assigned by the database when the instance saved first time.主键属性通常在实例第一次保存时由数据库分配。 So you can use something like if instance.pk is None所以你可以使用类似if instance.pk is None

According to the latest Django documentation , pre_save does NOT send a created argument.根据最新的 Django 文档pre_save不会发送created参数。 Post_save however does .但是Post_save确实如此 I could not find any reference of the signal sending created since version 1.0 .我找不到自版本 1.0以来created的信号发送的任何参考。

I am not sure if this is the recommended way but @Radagast's method didnt work for me(not sure if its because I use custom Pk's).我不确定这是否是推荐的方法,但@Radagast 的方法对我不起作用(不确定是否因为我使用自定义 Pk)。

I tried the following(not sure if this is the best way):我尝试了以下方法(不确定这是否是最好的方法):

@receiver(pre_save, sender=YourModelName, weak=False, )
def presave_payment_model_check(sender, instance=None, created=False, **kwargs):
    #Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate
    if instance._state.adding:
        # we would need to create the object
        print "Creating an object"
    else:
        #we are updating the object
        print "Updating an object"
    

Reference: Django : What is the role of ModelState?参考: Django:ModelState的作用是什么?

You can easily check if an instance is created or updated in pre_save in this way:您可以通过以下方式轻松检查是否在 pre_save中创建或更新了实例:

@receiver(pre_save, sender=MyModel)
def pre_save_user(sender, instance, **kwargs): 
    if instance._state.adding:
        print ('Instance created!')
    else:
        print ('Instance updated!')

Tested with Django 3.0.用 Django 3.0 测试。

使用 instance._state.adding 是最合乎逻辑的方法,因为无论主键是否已分配,您都可以判断模型状态是否存在。

You can try this.你可以试试这个。

@receiver(pre_save, sender=User)
def user(instance, *args, **kwargs):
    if instance.id != None:

When pk is a custom uuid field, instance.pk will also have value on create.当 pk 是自定义 uuid 字段时,instance.pk 也将在创建时具有值。

I am using Django's pre_save signal to implement auto_now_add.我正在使用Django的pre_save信号来实现auto_now_add。 There is a lot of discussion on the internet on why you should or shouldn't implement it yourself.互联网上有很多关于您为什么应该或不应该自己实施的讨论。 I do not appreciate comments on this.我不喜欢对此发表评论。 Neither on whether I should be rewriting the save function (I have a lot of models that use auto_now_add so using signals makes sense).无论我是否应该重写save函数(我都有很多使用auto_now_add的模型,因此使用信号很有意义)。

My question is:我的问题是:
I would like to check if the instance is created or updated.我想检查实例是否已创建或更新。 According to some sources on the internet this can be done by testing if kwargs['created'] is True.根据互联网上的一些消息来源,这可以通过测试kwargs['created']是否为True来完成。 However 'created' does not appear in my kwargs even though the instance is newly created.但是,即使实例是新创建的, 'created'也不会出现在我的kwargs I was just wondering if it has ever existed or that it has disappeared magically.我只是想知道它是否曾经存在过,或者它已经神奇地消失了。 I know I could also test if kwargs['instance'].id is set (this in fact works for me), but I'd like to know if kwargs['created'] still exists.我知道我也可以测试是否设置了kwargs['instance'].id (实际上对我有用),但是我想知道kwargs ['created']是否仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM