【发布时间】:2011-12-09 04:31:12
【问题描述】:
我在 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
附:我试过one of the solutions I found on the net,但它对我不起作用。
【问题讨论】:
-
我找到了the solution page in web archives。该解决方案有一个缺点 - 您应该在所有子类之后声明信号,否则它将找不到它们。
标签: python django django-signals