优化Django模型保存方法,用于访问上传的文件路径

时间:2014-08-30 17:50:13

标签: python django

在我的Django应用程序模型中,我需要在save()方法中访问ImageField,以便在保存整个模型实例之前提取一些gps信息并填充其他MyModel字段。

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    if self.image:
        # Todo: remove the double call of super(Photo, self).save() method by accessing the file before it will save
        super(Photo, self).save(force_insert, force_update, using, update_fields)
        image_file = gpsimage.open(self.image.path)  #gpsimage.open needs a file path that I can have it only after I call super(Photo, self).save(....)
        ...
        ...
        ...
        # Final save call
        super(Photo, self).save(force_insert, force_update, using, update_fields)

是否可以访问临时文件(图像)路径,从中提取信息,如果所有字段都有效,是否可以保存整个模型? 还有其他优雅的解决方案吗?

我当前的应用是一个REST和管理员应用,所以我希望在一个中心模型中添加这个逻辑。

2 个答案:

答案 0 :(得分:2)

您可以通过自定义保存方法访问文件路径,如下所示:self.myimg.name,其中myimg是您字段的名称。

from django.db import models
import uuid
import os

def img_file_path(instance, filename):
    ''' Creates a filepath and name for an image file. '''
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    today = datetime.date.today()
    return os.path.join('imgs', '%s/%s/%s' % (today.year, today.month, today.day), filename)

class MyModel(models.Model):
    myimg = models.ImageField(upload_to = img_file_path)

    def save(self, *args, **kwargs):
        path_of_file = self.myimg.name

        # edit path_of_file, or whatever
        self.myimg.name = path_of_file.upper()

        super(MyModel, self).save()

如果您查看the source code,则会在__init__()方法中确定文件名,因此一旦创建对象(在保存之前),您就可以访问它提交)。

答案 1 :(得分:0)

我有同样的问题,我的解决方案是保存两次。这是我的代码:

 26     def save(self, *args, **kwargs):
 27         super(GeoFile, self).save(*args, **kwargs)
 28         self.filetype = self.possible_type()
 29         if self.filetype == 'SHPZ':
 30             self.fileinfo = self.shpz_info()
 31             if 'srid' in self.fileinfo and not self.fileinfo['srid'] is None:
 32                 self.srid = self.fileinfo['srid']
 41         super(GeoFile, self).save()