Initiate save post on Django abstract parent model when child model is saved

I have these models:

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'

I need the book.save()SearchModel function to be called ( without any code changes in the book / without creating a save save message on Book )

My motivation is that each model inherited from SearchModel will have some post_save handler (without writing additional code, it only inherits Signal)

Is it possible?

+4
source share
1 answer

: "" 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 , .

+7

Source: https://habr.com/ru/post/1623111/


All Articles