今天染念用python写了用户上传头像的功能,当测试api的时候,发现数据库存的路径有些不对劲,以及服务器也没有上传得到图片
那么,我的代码是怎么样的呢?

User.objects.filter(uid=uid).update(avatar=avatar)

而改成

user_data = User.objects.get(uid=uid)
user_data.avatar = avatar
user_data.save()

惊奇的发现

  • 会自动保存文件路径到数据库
  • 会自动保存文件到指定路径
  • 必要时会自动创建目录。

在stackoverflow找到这样的文章

也就是说使用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.datetimedatetime

Insert 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会调用其他方法

版权属于:染念
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2021年04月29日 09:01
1
发表评论


180 文章数
673 评论量
4 分类数
184 页面数
已在风雨中度过 7年69天5小时48分
目录
来自 《django ImageField 上传不了文件?》
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部