Efficient way to update multiple fields of a Django model object

I am trying to update a user in a Django database.

The data obtained is as follows:

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

I get a user with this id as follows:

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 don't want to do this for every entry, so 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 does not work. Any idea how I can update a user without doing this for each entry?

+4
source share
3 answers

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

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

SQL update , . , User.

SQL . , , , select , , Django ORM .

+5

, .update() QuerySet :

my_id = fetched_data.pop('id')  # remove 'id' from `fetch_data`
                                # as it is not supposed to be updated

User.objects.filter(pk=my_id).update(**fetched_data)
#          unpack the content of `dict` ^

fetched_data dict User, fetched_data dict. pk, .

+7
setattr(old_user, fetched_data_key, fetched_data['fetched_data_key'])
+3
source

Source: https://habr.com/ru/post/1667265/


All Articles