这两种方法在Django ModelForm中覆盖save()方法有什么区别? [英] What's the difference between these two ways to override the save() method in a Django ModelForm?

查看:484
本文介绍了这两种方法在Django ModelForm中覆盖save()方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了两种这样做的方法。 这里接受的回答建议

  def save(self,* args,** kwargs):
instance = super(ModelClass,self).save(commit = False)
instance.my_stuff = manual_value
instance.save()

但是, a href =http://arunkreddy.com/2014/01/22/overriding-save-method-in-django-models/ =nofollow noreferrer>在这里找到,似乎更优雅: / p>

  def save(self,* args,** kwargs):
self.my_stuff = manual_value
super (ModelClass,self).save(* args,** kwargs)

有什么理由选择一个在另外一个,除了后者是一个较少的行,例如运行父 save()的原因之一?

解决方案

这两个例子正在做不同的事情。第一个是保存模型表单的保存方法,第二个是覆盖模型的保存方法。



如果要在每次保存模型时设置该值,则覆盖模型的方法是有意义的。如果更新该字段与表单相关联,则覆盖表单的保存方法是正确的。



在模型窗体的保存方法中,必须调用 save(commit = False)首先获取实例。我不会担心它是不合适的,这是Django中非常常见的模式,在这里记录


I've come across two methods of doing this. The accepted answer here suggests:

def save(self, *args, **kwargs):
    instance = super(ModelClass, self).save(commit=False)
    instance.my_stuff = manual_value
    instance.save()

But the following, found here, seems more elegant:

def save(self, *args, **kwargs):
    self.my_stuff = manual_value
    super(ModelClass, self).save(*args, **kwargs)

Is there any reason to choose one over the other, other than the latter being one less line, such as a reason for running the parent save() first?

解决方案

The two examples are doing different things. The first is saving the model form's save method, the second is overriding the model's save method.

It only makes sense to override the model's method if you want the value to be set every time the model is saved. If updating the field is related to the form, then overriding the form's save method is the correct thing to do.

In the model form's save method, you have to call save(commit=False) first to get the instance. I wouldn't worry about it being inelegant, it's a very common pattern in Django, and is documented here.

这篇关于这两种方法在Django ModelForm中覆盖save()方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆