我有这个型号:
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上创建post保存信号)
我的动机是每个模型都继承自SearchModel,会有一些post_save处理程序(不需要编写额外的代码 - 只继承Signal)
可能吗?
这很简单:连接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()
然后,您可以提供默认实现,SearchModel
并在子类中根据需要覆盖它.