2013-05-21 55 views
0

我嘗試在模型中覆蓋save()方法。如何正確執行此操作?在模型中重寫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

+0

創建只有當或每次它保存? –

回答

0
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() 
+0

@dev_fight您可以從字段獲取文件路徑,字段名稱不是文件名。我還沒有處理文件的經驗,但我認爲它應該是下列之一:'Image.open(self.base_file)或Image.open(self.base_file.file)或Image.open(self.base_file的.url)'。 –