Django:基本模型信号处理程序不触发
在以下示例代码中:
from django.db import models
from django.db.models.signals import pre_save
# Create your models here.
class Parent(models.Model):
name = models.CharField(max_length=64)
def save(self, **kwargs):
print "Parent save..."
super(Parent, self).save(**kwargs)
def pre_save_parent(**kwargs):
print "pre_save_parent"
pre_save.connect(pre_save_parent, Parent)
class Child(Parent):
color = models.CharField(max_length=64)
def save(self, **kwargs):
print "Child save..."
super(Child, self).save(**kwargs)
def pre_save_child(**kwargs):
print "pre_save_child"
pre_save.connect(pre_save_child, Child)
创建子级时 pre_save_parent
不会触发:
child = models.Child.objects.create(color="red")
这是预期的行为吗?
In the following sample code:
from django.db import models
from django.db.models.signals import pre_save
# Create your models here.
class Parent(models.Model):
name = models.CharField(max_length=64)
def save(self, **kwargs):
print "Parent save..."
super(Parent, self).save(**kwargs)
def pre_save_parent(**kwargs):
print "pre_save_parent"
pre_save.connect(pre_save_parent, Parent)
class Child(Parent):
color = models.CharField(max_length=64)
def save(self, **kwargs):
print "Child save..."
super(Child, self).save(**kwargs)
def pre_save_child(**kwargs):
print "pre_save_child"
pre_save.connect(pre_save_child, Child)
pre_save_parent
doesn't fire when I a Child is created:
child = models.Child.objects.create(color="red")
Is this expected behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个关于此问题的开放票证,#9318。
你的解决方法看起来不错。以下是 benbest86 和 alexr 分别。
监听子类信号,并向那里发送父类信号。
连接信号时不要指定发送者,然后检查父类的子类。
There's an open ticket about this, #9318.
Your workaround looks fine. Here are two others suggested on the ticket by benbest86 and alexr respectively.
Listen on the child class signal, and send the Parent signal there.
Do not specify the sender when connecting the signal, then check for subclasses of parent.
我没有意识到
sender
是connect
的可选参数。我可以执行以下操作:这允许我为每个模型编写
pre_save
方法,并且它们反过来可以调用任何基类版本(如果存在)。还有更好的解决方案吗?
I didn't realise
sender
was an optional parameter toconnect
. I can do the following:This allows me to write per Model
pre_save
methods, and they in turn can call any base class versions (if they exists).Any better solutions?