覆盖Model中的save()方法。怎么做到这一点?

时间:2013-05-21 14:06:49

标签: django

我尝试覆盖Model中的save()方法。如何正确地做到这一点?

import Image
from tesseract import image_to_string

class FileModel(models.Model):
    user = models.ForeignKey(User)
    base_file = models.FileField(upload_to="files")
    after_file = models.FileField(upload_to="file_ocr", blank=True, null=True)

   def save(self):
       after_file = image_to_string(Image.open('base_file'), lang='en')
       after_file.save()
       super(FileModel, self).save()

如果创建了base_file,我需要使用image_to_string()方法并保存after_file之类的结果。

1 个答案:

答案 0 :(得分:1)

def save(self, *args, **kwargs):
    creating = self.pk is None
    super(FileModel, self).save(*args, **kwargs)
    if creating:
        self.after_file = image_to_string(Image.open('base_file'), lang='en')
        self.after_file.save()

或信号:

from django.db.models import signals
from django.dispatch import receiver

@receiver(signals.post_save, sender=FileModel)
def create_file(sender, instance, created, *args, **kwargs):
    if created:
        instance.after_file = image_to_string(Image.open('base_file'), lang='en')
        instance.after_file.save()