我设法让继承的信号接收器与@receiver
装饰器一起工作。查看相关的 Django 文档
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Animal(models.Model):
category = models.CharField(max_length=20)
@receiver(post_save)
def echo_category(sender, **kwargs):
print ("category: '%s'" % kwargs['instance'].category)
class Dog(Animal):
color = models.CharField(max_length=10)
此解决方案在Python 3.6.8 Django 2.2中有效
当我这样做时
>>> from myapp.models import Dog
>>> dog = Dog()
>>> dog.category = "canine"
>>> dog.save()
category: 'canine'
>>>
没问题。一切似乎都在外壳上工作。
有点不相关,但是当我通过管理面板编辑模型时,它被调用了两次,所以我通过检查'created'
kwarg 来过滤它们。在一个调用中它是假的,另一个是真的,所以我只是放入了一个简单的 if 块。该解决方法的功劳归功于 Pratik Mandrekar和他的回答:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Animal(models.Model):
category = models.CharField(max_length=20)
@receiver(post_save)
def echo_category(sender, **kwargs):
if not kwargs.get('created'):
print ("category: '%s'" % kwargs['instance'].category)
class Dog(Animal):
color = models.CharField(max_length=10)