【问题标题】:While saving a Django model instance, in what order are my clean() and save() overrides applied relative to methods used as ModelField attributes?在保存 Django 模型实例时,相对于用作 ModelField 属性的方法,我的 clean() 和 save() 覆盖应用的顺序是什么?
【发布时间】:2012-04-15 19:13:57
【问题描述】:

我有一个带有first_namelast_name 字段的模型,它们用于在ImageField 上创建文件名。 ImageField 上的 upload_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(' \t\r\n')

【问题讨论】:

    标签: django django-models save


    【解决方案1】:

    如果upload_to 参数有一个可调用对象,它会在模型​​库的save() 方法中调用。 save() 当然是在 clean() 之后调用的,所以如果你已经在 clean() 方法中删除了任何字段,则不需要删除任何字段。

    你可以在Django源代码的第85行看到代码被调用的地方:https://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py

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

    所以,顺序是form submit -> model.full_clean() -> overridden clean() -> save(),调用upload_to()

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2016-10-18
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多