这里的save()函数是什么用法?参数commit=False不传的话会报错。
来源:6-11 完善地址编辑
lin丶林
2019-12-20 15:45:36
obj = super().save()会报错:django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null")
obj = super().save(commit=False)传入commit=False没有问题。
obj.save()默认commit=True?,又不报错,'user_id=NULL..
调用super().save()得到对象,通过该对象重写save()方法,没有返回对象。
能解释下上面4点吗?好难懂。。。
1回答
好帮手乔木
2019-12-20
同学你好:
保存此表单本身。如果commit=True,则为实例对象。
在Django文档关于commit=False有一段解释:
This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database.
In this case, it's up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.
大致理解:
当你通过表单获取你的模型数据,但是需要给模型里null=False字段添加一些非表单的数据,该方法会非常有用。如果你指定commit=False,那么save方法不会理解将表单数据存储到数据库,而是给你返回一个当前对象。这时你可以添加表单以外的额外数据,再一起存储。
在视频中,修改或者添加地址。同学不能直接去保存,region不是这个UserAddress这个模型的字段。而且这个模型中,user,province, city, area都是不能为空的,需要给这些字段设置值,然后再进行保存。因此需要先得到一个对象,给这个对象的不为空的字段定义值后再保存。province, city, area这三个就不是直接从表单获取的值,而是从表单数据字段为region的值分割的。所以为commit=True时,报错说这个对象有字段不能为空。
如果我解决了同学的问题,请采纳!学习愉快^_^。
相似问题