2
我需要在查询集加载的每个实例上调用实例方法。我可以使用pre_init/post_init信号吗?当QuerySet加载实例时,Django是否发送信号pre_init/post_init?
我需要在查询集加载的每个实例上调用实例方法。我可以使用pre_init/post_init信号吗?当QuerySet加载实例时,Django是否发送信号pre_init/post_init?
是的,即使从查询集创建实例时,也会发送pre_init/post_init。
不要把我的话,试试吧例如: -
def pre_init_callback(sender, **kwargs):
print 'pre_init', sender, kwargs
pre_init.connect(pre_init_callback)
def post_init_callback(sender, **kwargs):
print 'post_init', sender, kwargs
post_init.connect(post_init_callback)
将输出类似:
In [5]: list(Profile.objects.all())
pre_init <class 'testapp.models.Profile'> {'signal': <django.dispatch.dispatcher.Signal object at 0x15e6450>, 'args': (1, False, None), 'kwargs': {}}
post_init <class 'testapp.models.Profile'> {'instance': <Profile: Profile object>, 'signal': <django.dispatch.dispatcher.Signal object at 0x15e6490>}
pre_init <class 'testapp.models.Profile'> {'signal': <django.dispatch.dispatcher.Signal object at 0x15e6450>, 'args': (2, False, None), 'kwargs': {}}
post_init <class 'testapp.models.Profile'> {'instance': <Profile: Profile object>, 'signal': <django.dispatch.dispatcher.Signal object at 0x15e6490>}
Out[5]: [<Profile: Profile object>, <Profile: Profile object>]