更新Django模型对象的多个字段的有效方法 [英] Efficient way to update multiple fields of Django model object

查看:172
本文介绍了更新Django模型对象的多个字段的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新Django数据库中的用户。

I'm trying to update user in Django database.

获取的数据如下:

fetched_data = {
     'id': 1,
     'first_name': 'John',
     'last_name': 'Doe',
     'phone': '+32 12',
     'mobile_phone': '+32 13',
     'email': 'myemail@hotmail.com',
     'username': 'myusername'
}

我使用以下 id 获取用户:

old_user = User.objects.get(pk=fetched_data['id'])

如果我按如下方式更新用户:

If I update the user as follows :

old_user.username = fetched_data['username']
old_user.first_name = fetched_data['first_name']
......
old_user.save()

工作正常,但我不想为每条记录都这样做,因此我尝试了类似的操作:

it works fine, but I do not want to do it for every record, thus I tried something like :

for fetched_data_key in fetched_data:
    old_user.fetched_data_key = fetched_data['fetched_data_key']
    //old_user[fetched_data_key] = fetched_data['fetched_data_key'] --- I tried this way to
    old_user.save()

但这不起作用。知道如何在不对每个记录执行操作的情况下更新用户吗?

But that doesn't work. Any idea how can I update the user without doing it for every record?

推荐答案

您可以在不获取数据的情况下更新数据库中的行并反序列化; update() 可以做到。例如:

You can update a row in the database without fetching and deserializing it; update() can do it. E.g.:

User.objects.filter(id=data['id']).update(email=data['email'], phone=data['phone'])

这将发出一个SQL update 语句,并且比您帖子中的代码快得多。它永远不会获取数据或浪费时间来创建 User 对象。

This will issue one SQL update statement, and is much faster than the code in your post. It will never fetch the data or waste time creating a User object.

尽管如此,您不能发送全部一堆更新数据到SQL数据库,并要求它一次将其映射到不同的行。如果您需要像这样快速进行的大规模更新,则最好的选择是将数据插入单独的表中,然后将其更新为在该表上选择 。据我所知,Django ORM不支持此功能。

You cannot, though, send a whole bunch of update data to the SQL database and ask it to map it to different rows in one go. If you need a massive update like that done very quickly, your best bet is probably inserting the data into a separate table and then update it form a select on that table. Django ORM does not support this, as far as I can tell.

这篇关于更新Django模型对象的多个字段的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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