python – Django:基本模型信号处理程序不会触发

前端之家收集整理的这篇文章主要介绍了python – 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)

创建Child时,pre_save_parent不会触发:

child = models.Child.objects.create(color="red")

这是预期的行为吗?

解决方法

这是一个关于这个的开放票,#9318.

你的解决方法看起来很好.以下是分别于benbest86alexr在机票上提出的另外两项建议.

>听取子类信号,并在那里发送父信号.

def call_parent_pre_save(sender,instance,created,**kwargs):
    pre_save.send(sender=Parent,instance=Parent.objects.get(id=instance.id),created=created,**kwargs)
pre_save.connect(call_parent_pre_save,sender=Child)

>连接信号时不要指定发送方,然后检查父类的子类.

def pre_save_parent(sender,**kwargs):
    if not isinstance(instance,Parent):
        return
    #do normal signal stuff here
    print "pre_save_parent"

pre_save.connect(pre_save_parent)
原文链接:https://www.f2er.com/python/241917.html

猜你在找的Python相关文章