在Django中写保存功能的位置?

时间:2016-09-29 04:12:19

标签: python django django-models django-forms

我应该在Django中将save()函数写在哪里:在模型类中的models.py或表单中的forms.py中?

例如: models.py

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

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

forms.py

class  Addcustomer(forms.ModelForm):
   class Meta:
       model = Customer
       fields = ('name',)
   def save():
     ........code to override it.... 

我应该在哪里覆盖我的保存功能?

1 个答案:

答案 0 :(得分:0)

这取决于你想要实现的目标。默认实现ModelForm的保存调用Model的保存。但通常最好在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