Tôi có một vài cấp độ mô hình thừa kế trong Django:Làm thế nào để sử dụng mô hình kế thừa Django với tín hiệu?
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()
Có rất nhiều mô hình khác nhau kế thừa từ WorkAttachmentFileBased
và WorkAttachment
. Tôi muốn tạo một tín hiệu, sẽ cập nhật một trường attachment_count
cho công việc của phụ huynh, khi tệp đính kèm được tạo. Nó sẽ là hợp lý, để nghĩ rằng tín hiệu được thực hiện cho người gửi cha mẹ (WorkAttachment
) sẽ chạy cho tất cả các mô hình kế thừa quá, nhưng nó không. Đây là mã của tôi:
@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()
Có cách nào để làm cho tín hiệu này hoạt động cho tất cả các kiểu được kế thừa từ WorkAttachment
?
Python 2.7, Django 1.4 pre-alpha
P.S. Tôi đã thử one of the solutions I found on the net, nhưng nó không hoạt động đối với tôi.
Giải pháp liên kết bị phá vỡ – Martin
tôi đã tìm thấy [trang giải pháp trong tài liệu lưu trữ web] (http: // web. archive.org/web/20120715042306/http://codeblogging.net/blogs/1/14). Có một nhược điểm của giải pháp - bạn nên khai báo tín hiệu sau tất cả các lớp con, nếu không nó sẽ không tìm thấy chúng. – HighCat