How to use Django model inheritance with signals?

前端 未结 8 813
无人共我
无人共我 2020-12-23 11:15

I have a few model inheritance levels in Django:

class WorkAttachment(models.Model):
    \"\"\" Abstract class that holds all fields that are required in eac         


        
8条回答
  •  忘掉有多难
    2020-12-23 12:03

    I just did this using python's (relatively) new __init_subclass__ method:

    from django.db import models
    
    def perform_on_save(*args, **kw):
        print("Doing something important after saving.")
    
    class ParentClass(models.Model):
        class Meta:
            abstract = True
    
        @classmethod
        def __init_subclass__(cls, **kwargs):
            super().__init_subclass__(**kwargs)
            models.signals.post_save.connect(perform_on_save, sender=cls)
    
    class MySubclass(ParentClass):
        pass  # signal automatically gets connected.
    

    This requires django 2.1 and python 3.6 or better. Note that the @classmethod line seems to be required when working with the django model and associated metaclass even though it's not required according to the official python docs.

提交回复
热议问题