小编典典

如何在信号中使用Django模型继承?

python

我在Django中有一些模型继承级别:

class WorkAttachment(models.Model):
    """ Abstract class that holds all fields that are required in each attachment """
    work            = models.ForeignKey(Work)
    added           = models.DateTimeField(default=datetime.datetime.now)
    views           = models.IntegerField(default=0)

    class Meta:
        abstract = True


class WorkAttachmentFileBased(WorkAttachment):
    """ Another base class, but for file based attachments """
    description     = models.CharField(max_length=500, blank=True)
    size            = models.IntegerField(verbose_name=_('size in bytes'))

    class Meta:
        abstract = True


class WorkAttachmentPicture(WorkAttachmentFileBased):
    """ Picture attached to work """
    image           = models.ImageField(upload_to='works/images', width_field='width', height_field='height')
    width           = models.IntegerField()
    height          = models.IntegerField()

WorkAttachmentFileBased和继承了许多不同的模型WorkAttachment。我想创建一个信号attachment_count,当创建附件时,该信号将更新父工作的字段。认为为父发件人(WorkAttachment)发出的信号也会在所有继承的模型上运行,这是合乎逻辑的,但事实并非如此。这是我的代码:

@receiver(post_save, sender=WorkAttachment, dispatch_uid="att_post_save")
def update_attachment_count_on_save(sender, instance, **kwargs):
    """ Update file count for work when attachment was saved."""
    instance.work.attachment_count += 1
    instance.work.save()

有没有办法使此信号对所有继承自其的模型起作用WorkAttachment

Python 2.7,Django 1.4 pre-alpha

附言:我已经尝试了在网上找到的一种解决方案,但是它对我不起作用。


阅读 135

收藏
2021-01-20

共1个答案

小编典典

您可以尝试类似:

model_classes = [WorkAttachment, WorkAttachmentFileBased, WorkAttachmentPicture, ...]

def update_attachment_count_on_save(sender, instance, **kwargs):
    instance.work.attachment_count += 1
    instance.work.save()

for model_class in model_classes:
    post_save.connect(update_attachment_count_on_save, 
                      sender=model_class, 
                      dispatch_uid="att_post_save_"+model_class.__name__)

(免责声明:我尚未测试以上内容)

2021-01-20