Django学习笔记4(ModelForm.save(commit=False))

前端之家收集整理的这篇文章主要介绍了Django学习笔记4(ModelForm.save(commit=False))前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.ModelForm.save()

`ModelForm.save(commit=False)`可以先不保存到数据库,返回一个数据库对象,之后再用数据库对象save()。commit默认是True,也就是默认直接保存了。
```
if comment_form.is_valid():

new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()

```


另外,如果ModelForm的模型有ManyToMany的关系,需要在最后需要调用save_m2m()

# Create a form instance with POST data.
>>> f = AuthorForm(request.POST)

Create,but don't save the new author instance.

new_author = f.save(commit=False)

Modify the author in some way.

new_author.some_field = 'some_value'

Save the new instance.

new_author.save()

Now,save the many-to-many data for the form.

f.save_m2m()

猜你在找的Django相关文章