保存子模型时,在Django抽象父模型上启动保存

时间:2016-01-06 14:56:15

标签: python django abstract-class

我有这个型号:

from django.db.models import Model

class SearchModel(Model):  
    class Meta:
        abstract = True

class Book(SearchModel):

    book_id = django_models.BigIntegerField(null=True, blank=True)

    class Meta:
        db_table = 'book'

我需要在book.save()上调用一个SearchModel函数(在Book上没有任何代码更改/不在Book上创建保存信号

我的动机是每个模型都继承自SearchModel,会有一些post_save处理程序(不需要编写额外的代码 - 只能继承Signal)

有可能吗?

2 个答案:

答案 0 :(得分:8)

这很简单:不提供任何特定的发件人"连接post_save处理程序时,然后在处理程序中检查senderSearchModel的子类,即:

from django.db.signals import post_save
from django.dispatch import receiver
from django.db.models import Model

class SearchModel(Model):  
    class Meta:
        abstract = True

    def on_post_save(self):
        print "%s.on_post_save()" % self

# NB `SearchModel` already inherits from `Model` 
class Book(SearchModel):
    book_id = django_models.BigIntegerField(null=True, blank=True)

    class Meta:
        db_table = 'book'


@receiver(post_save)
def search_on_post_save(sender, instance, **kwargs):
    if issubclass(sender, SearchModel):
         instance.on_post_save()

然后,您可以在SearchModel中提供默认实现,并在子类中根据需要覆盖它。

答案 1 :(得分:0)

signals.py

from django.db.signals import post_save

def search_on_post_save(sender, instance, **kwargs):
    pass

for subclass in SearchModel.__subclasses__():
    post_save.connect(search_on_post_save, subclass)