在Django中把save函数写在哪里?

2024-04-25 10:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该在Django中的什么地方编写我的save()函数:在模型类的models.py中,还是在{}中的表单中?在

例如: 模型.py在

class Customer(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(User)

    def save():
      ........ some code to override it.......

在表单.py在

^{pr2}$

我应该在哪里重写保存函数?在


Tags: django函数namepy模型表单modelmodels
1条回答
网友
1楼 · 发布于 2024-04-25 10:15:05

这取决于你想达到什么目标。ModelForm的save调用Model的save的默认实现。但通常最好在form上重写它,因为它还运行验证。所以如果您已经在使用form,我建议重写ModelForm.save。重写是指使用super进行扩展

以下是ModelForm.save的默认实现

def save(self, commit=True):
    """
    Save this form's self.instance object if commit=True. Otherwise, add
    a save_m2m() method to the form which can be called after the instance
    is saved manually at a later time. Return the model instance.
    """
    if self.errors: # there validation is done
        raise ValueError(
            "The %s could not be %s because the data didn't validate." % (
                self.instance._meta.object_name,
                'created' if self.instance._state.adding else 'changed',
            )
        )
    if commit:
        # If committing, save the instance and the m2m data immediately.
        self.instance.save()
        self._save_m2m()
    else:
        # If not committing, add a method to the form to allow deferred
        # saving of m2m data.
        self.save_m2m = self._save_m2m
    return self.instance

save.alters_data = True

相关问题 更多 >

    热门问题