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

Eya*_* Ch 4 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'
Run Code Online (Sandbox Code Playgroud)

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

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

可能吗?

bru*_*ers 9

这很简单:连接post_save处理程序时不提供任何特定的"发送者" ,然后在处理程序中检查是否sender是子类SearchModel,即:

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()
Run Code Online (Sandbox Code Playgroud)

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

  • 但它有一个小缺点,它调用每个调用save()的模型 (4认同)