我需要在查询集加载的每个实例上调用实例方法。我可以使用pre_init / post_init信号吗?
答案 0 :(得分:8)
是的,即使从查询集创建实例,也会发送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>]