我有一个Notification
模型,该模型使用Django通用外键,因此可以通知用户。
class Notification(models.Model):
target_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE)
target_id = models.CharField(max_length=36)
target = GenericForeignKey('target_ct', 'target_id')
target_user = models.ForeignKey(User, on_delete=models.CASCADE)
删除生成此类通知的对象时,我想删除所有相关通知。
到目前为止,我已经实现了对每个模型使用post_delete信号,例如。
@receiver(post_delete, sender=Model1)
def delete(sender, instance, *args, **kwargs):
Notification.objects.filter(target_id=instance.id, target_ct=ContentType.objects.get_for_model(instance)).delete()
@receiver(post_delete, sender=Model2)
def delete(sender, instance, *args, **kwargs):
Notification.objects.filter(target_id=instance.id, target_ct=ContentType.objects.get_for_model(instance)).delete()
我大约有20个模型,有没有一种方法可以生成适用于每个模型的post_delete信号?