Django: save()方法的形式还是模型?

时间:2021-04-16 00:25:31

quite a generic question here but I was curious as to when and in what cases would you use a save method in a ModelForm over the Model class itself and vice versa?

这里有一个很普通的问题,但我很好奇什么时候,在什么情况下,你会在模型类的模型中使用一个保存方法,反之亦然?

model:

模型:

class Model(models.Model):
...
    def save(self, *args, **kwargs):
        super (Model, self).save(*args, **kwargs)

modelform:

modelform:

class ModelForm(forms.ModelForm):
...
    def save(self, commit=True):
        model = super(ModelForm, self).save(commit=True)
        if commit:
            model.save()
        return model

Thanks!

谢谢!

2 个解决方案

#1


0  

Both are overwriting the default method. Only difference is that Model.save is saving object attributes but ModelForm.save is saving form data. ModelForm is not just a simple Form. It linked to model instance. So it automatically access the fields of corresponding models.

两者都覆盖了默认的方法。唯一不同的是这个模型。保存是保存对象属性,但是是ModelForm。保存是保存表单数据。ModelForm不仅仅是一个简单的表单。它链接到模型实例。因此它会自动访问相应模型的字段。

#2


0  

The difference depends on your need/usage. If you know objects will be always be created using ModelForm then you put your logic in ModelForm.save to do stuff which is required before or after saving the data. If you know the objects could be created directly as well which obviously does not go through ModelForm you then write your logic in Model.save to ensure integrirty/consistentency of data. But this does not mean that overriding save both on ModelForm and Model itself is bad, again there will be scenarios where you need both.

区别取决于你的需要/使用。如果您知道对象将总是使用ModelForm创建,那么您可以将您的逻辑放入ModelForm中。保存在保存数据之前或之后需要做的事情。如果您知道对象可以直接创建,那么显然不需要通过ModelForm,那么您就可以在模型中编写逻辑。保存以确保数据的完整性/一致性。但是,这并不意味着在ModelForm和模型本身上重写保存都是不好的,同样会出现需要两者同时使用的场景。

#1


0  

Both are overwriting the default method. Only difference is that Model.save is saving object attributes but ModelForm.save is saving form data. ModelForm is not just a simple Form. It linked to model instance. So it automatically access the fields of corresponding models.

两者都覆盖了默认的方法。唯一不同的是这个模型。保存是保存对象属性,但是是ModelForm。保存是保存表单数据。ModelForm不仅仅是一个简单的表单。它链接到模型实例。因此它会自动访问相应模型的字段。

#2


0  

The difference depends on your need/usage. If you know objects will be always be created using ModelForm then you put your logic in ModelForm.save to do stuff which is required before or after saving the data. If you know the objects could be created directly as well which obviously does not go through ModelForm you then write your logic in Model.save to ensure integrirty/consistentency of data. But this does not mean that overriding save both on ModelForm and Model itself is bad, again there will be scenarios where you need both.

区别取决于你的需要/使用。如果您知道对象将总是使用ModelForm创建,那么您可以将您的逻辑放入ModelForm中。保存在保存数据之前或之后需要做的事情。如果您知道对象可以直接创建,那么显然不需要通过ModelForm,那么您就可以在模型中编写逻辑。保存以确保数据的完整性/一致性。但是,这并不意味着在ModelForm和模型本身上重写保存都是不好的,同样会出现需要两者同时使用的场景。