热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Django:基本模型信号处理程序不会触发-Django:basemodelsignalhandlerdoesn'tfire

Inthefollowingsamplecode:在以下示例代码中:fromdjango.dbimportmodelsfromdjango.db.models.signals

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时,pre_save_parent不会触发:

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

Is this expected behaviour?

这是预期的行为吗?

2 个解决方案

#1


6  

There's an open ticket about this, #9318.

有关于此的公开票,#9318。

Your workaround looks fine. Here are two others suggested on the ticket by benbest86 and alexr respectively.

你的解决方法看起来很好。以下是benbest86和alexr分别在票上建议的其他两个。

  1. Listen on the child class signal, and send the Parent signal there.

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

    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)
    
  2. Do not specify the sender when connecting the signal, then check for subclasses of parent.

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

    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)
    

#2


2  

I didn't realise sender was an optional parameter to connect. I can do the following:

我没有意识到sender是一个可选的连接参数。我可以做以下事情:

def pre_save_handler(**kwargs):
    instance = kwargs['instance']
    if hasattr(instance, 'pre_save'):
        instance.pre_save()
pre_save.connect(pre_save_handler)

This allows me to write per Model pre_save methods, and they in turn can call any base class versions (if they exists).

这允许我按照模型pre_save方法编写,然后它们可以调用任何基类版本(如果它们存在)。

Any better solutions?

更好的解决方案?


推荐阅读
author-avatar
不是我的这
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有