Hey*_*yl1 21 python django kwargs
我正在使用Django的pre_save信号来实现auto_now_add.互联网上有很多关于为什么你应该或不应该自己实现它的讨论.我不赞赏对此的评论.我是否应该重写保存功能(我有很多使用auto_now_add的模型,所以使用信号是有意义的).
我的问题是:
我想检查实例是否已创建或更新.根据互联网上的一些消息来源,可以通过测试是否kwargs['created']为True 来完成.但是'created',kwargs即使实例是新创建的,也不会出现在我的脑中.我只是想知道它是否曾经存在过,或者它已经神奇地消失了.我知道我也可以测试是否kwargs['instance'].id已设置(这实际上对我有用),但我想知道kwargs ['created']是否仍然存在.
Pra*_*rma 16
我不确定这是否是推荐的方式,但@ Radagast的方法对我不起作用(不确定它是否因为我使用自定义Pk).
我尝试了以下(不确定这是否是最佳方式):
@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 is True:
# we would need to create the object
print "Creating an object"
else:
#we are updating the object
print "Updating an object"
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过以下方式轻松检查是否在 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!')
Run Code Online (Sandbox Code Playgroud)
用 Django 3.0 测试。
| 归档时间: |
|
| 查看次数: |
14533 次 |
| 最近记录: |