मैं Django में कुछ मॉडल विरासत स्तर है:सिग्नल के साथ 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
से विरासत में मिली सभी मॉडलों के लिए यह संकेत काम करने के लिए एक तरह से: यहाँ मेरी कोड है?
अजगर 2.7, Django 1.4 पूर्व अल्फा
पी.एस. मैंने one of the solutions I found on the net की कोशिश की है, लेकिन यह मेरे लिए काम नहीं करता है।
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__)
: - यह सोचते हैं आप आधार वर्ग और उपवर्गों है (अस्वीकरण: मैं ऊपर का परीक्षण नहीं किया)
समाधान लिंक – Martin
मैं [वेब अभिलेखागार में समाधान पेज] (http पाया है टूट गया है। archive.org/web/20120715042306/http://codeblogging.net/blogs/1/14)। समाधान की एक कमी है - आपको सभी उप-वर्गों के बाद संकेत घोषित करना चाहिए, अन्यथा यह उन्हें नहीं मिलेगा। – HighCat