是否可以选择性地抑制Django中的post_save(或其他)信号? [英] Is it possible to selectively suppress a post_save (or other) signal in Django?

查看:152
本文介绍了是否可以选择性地抑制Django中的post_save(或其他)信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以有选择地抑制Django信号(例如 post_save post_init )对象创建,或者发送一些参数。

I'm wondering whether it's possible to selectively suppress a Django signal (such as post_save or post_init) on object creation, or, alternatively, send it certain parameters.

我有一个用户对象,它可以可以在我的代码中以许多不同的方式和位置创建。所以要为每个用户自动分配一个自定义的配置文件对象,我使用 post_save 信号。但是,在一个特定情况下,我需要绑定到创建的配置文件对象的额外信息。将它作为参数传递给 post_save 信号将是巨大的,但它看起来不太可能。

What I have is a User object, which can be created in many different ways and places in my code. So to automatically assign a custom Profile object to each User, I use the post_save signal. However, in one specific case, there is extra information that I want to bind to the created Profile object. Passing it as arguments to the post_save signal would be great, but it doesn't look possible.

另一个选项是手动创建个人资料对象,但后来我需要用户被保存,否则配置文件不能绑定到用户实例。然而,保存用户实例会导致另一个 Profile 通过信号调用的函数创建。

The other option is to manually create the Profile object, but then I need to that after the User is saved, otherwise the Profile cannot be bound to a User instance. Saving the User instance, however, results in another Profile being created via the function called by the signal.

我不能只是得到刚刚创建的个人资料对象,因为这导致一个 'Profile'对象是unsubscriptable 错误。任何建议?

And I can't just get the just-created Profile object, since that results in a 'Profile' object is unsubscriptable error. Any advice?

更新:

这是一个可能的情况的例子:

Here is an example of a possible situation:

def createUserProfile(sender, instance, created, **kwargs):
if created:  
    profile, created = Profile.objects.get_or_create(user=instance)
    if extra_param:
        profile.extra_param = extra_param
    profile.save()

post_save.connect(createUserProfile, sender=User)

def signup(request):
   ...
   extra_param = 'param'
   user.save()

如何在<$ c中获取变量 extra_param $ c> signup 方法到createUserProfile方法,它将作为配置文件对象的一部分存储在其中?

How do I get the variable extra_param in the signup method to the createUserProfile method, where it is to be stored as part of the Profile object?

推荐答案

为什么这不适合你?

user = User(...)
user.save()
# profile has been created transparently by post_save event
profile = user.profile
profile.extra_stuff = '...'
profile.save()

如果你痴迷于传递给事件的参数,可能是邪恶的:

If you are obsessed with parameters passing to event, possible but evil:

user = User()
user._evil_extra_args = { ... }
user.save()

In event:
extra_args = getattr(user, '_evil_extra_args', False)

它是邪恶的,因为读取你的代码的人将不知道那些_evil_extra_args是什么,它是如何工作。

It is evil because people who will read your code will have no idea what the heck those _evil_extra_args is for and how does it work.

这篇关于是否可以选择性地抑制Django中的post_save(或其他)信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆