2016-01-06 17 views
4

我有這個型號:啓動後保存在Django的抽象父模型中,當兒童模特保存

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功能應該被稱爲(不會對書/沒有創造任何代碼更改保存後的圖書

我的動機是,每一個模型從SearchModel繼承,會有一些post_save處理器(無需編寫額外的代碼信號 - 只有繼承信號)

可能嗎?

回答

7

這是相當簡單:不提供任何具體的「發件人」連接你的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中默認實現,如果需要在子類中覆蓋它。

+0

有必要嗎? '類書(模型,SearchModel)'?我們可以做這個'Book Book(SearchModel)'。有什麼不同嗎? –

+0

不,我只是複製/粘貼這部分代碼,但它確實應該是「class Book(SearchModel)'」。我編輯了我的答案,thx。 –

+0

是它的必要條件,我只是在這裏添加了兩個都繼承自Model,但實際上它繼承了更多的類 –