在保存Django模型实例时,相对于用作ModelField属性的方法,我的clean()和save()重写的应用顺序是



我有一个带有first_namelast_name字段的模型,它们用于在ImageField上创建文件名。ImageFieldupload_to的参数是使用此实例的信息生成文件名的方法。

保存此模型实例时,在clean()中对.strip()的调用用于生成文件名之前,是否会应用于字段?或者,当数据被使用时,我是否需要对其进行.strip()处理,以及在清理中?

models.py:

def set_path(instance, filename):
    """
    Set the path to be used for images uploaded (trainer photos).
    """
    return u'about/%(first)s_%(last)s.%(ext)s' % {
        'first': instance.first_name.strip(' t').lower(), #.strip() required?
        'last': instance.last_name.strip(' t').lower(), #.strip() required?
        'ext': filename.split('.')[-1]
    }
class Trainer(models.Model):
    """
    Trainers and their associated information.
    """
    first_name = models.CharField(max_length=25)
    last_name = models.CharField(max_length=25)
    image = models.ImageField(upload_to=set_path, blank=True, null=True,
        verbose_name="Trainer image")
    description = models.TextField()
    class Meta:
        unique_together = ('first_name', 'last_name',)
    def clean(self):
        super(Trainer, self).clean()
        # Are these calls to .strip() applied before the fields
        # get used as `instance` to determine a filename?
        self.first_name = self.first_name.strip(' t')
        self.last_name = self.last_name.strip(' t')
        self.description = self.description.strip(' trn')

如果upload_to参数有一个可调用的参数,则在模型库的save()方法期间调用它。save()当然是在clean()之后调用的,所以如果您已经在clean)方法中对任何字段进行了strip()操作,那么就不需要对其进行strip。

您可以在Django源代码的第90行看到代码的调用位置:https://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py

generate_filename是存储的变量,它指向您传递到upload_to中的任何内容。

因此,订单是表单提交->model.full_clean()->重写的clean()->save(),它调用upload_to()

相关内容

最新更新