今天染念用python写了用户上传头像的功能,当测试api的时候,发现数据库存的路径有些不对劲,以及服务器也没有上传得到图片
那么,我的代码是怎么样的呢?
User.objects.filter(uid=uid).update(avatar=avatar)
而改成
user_data = User.objects.get(uid=uid)
user_data.avatar = avatar
user_data.save()
惊奇的发现
- 会自动保存文件路径到数据库
- 会自动保存文件到指定路径
- 必要时会自动创建目录。
也就是说使用save,如果某些模型具有重写的保存方法,则必须避免使用update,或者找到另一种方法对该重写的方法执行任何操作方法(因此你去百度的时候,就会看到django上传图片的两种写法,有些人会在视图层写with文件的写入,这是因为他们使用update)
但不能完全否认update,毕竟批量更新数据挺香的,并且没有把对象加到内存中,也因此只有更新数据的作用把
What happens when you save?¶ When you save an object, Django performs
the following steps:Emit a pre-save signal. The pre_save signal is sent, allowing any
functions listening for that signal to do something.Preprocess the data. Each field's pre_save() method is called to
perform any automated data modification that's needed. For example,
the date/time fields override to implement auto_now_add and
auto_now.pre_save()Prepare the data for the database. Each field's get_db_prep_save()
method is asked to provide its current value in a data type that can
be written to the database.Most fields don't require data preparation. Simple data types, such as
integers and strings, are 'ready to write' as a Python object.
However, more complex data types often require some modification.For example, DateField fields use a Python object to store data.
Databases don't store objects, so the field value must be converted
into an ISO-compliant date string for insertion into the
database.datetimedatetimeInsert the data into the database. The preprocessed, prepared data is
composed into an SQL statement for insertion into the database.Emit a post-save signal. The post_save signal is sent, allowing any
functions listening for that signal to do something.
这是摘抄官方文档的说明,同样说了save会调用其他方法