How to update django database with a list of dictionary items?

Question:

I have a list of key value pairs here.

stat = [{‘id’: 1, ‘status’: ‘Not Fixed’}, {‘id’: 2, ‘status’: ‘Not Fixed’}, {‘id’: 4, ‘status’: ‘Not Fixed’}, {‘id’: 5, ‘status’: ‘Not Fixed’}, {‘id’: 6, ‘status’: ‘Not Fixed’}, {‘id’: 7, ‘status’: ‘Not Fixed’}]

The id in this list represents the id(primary key) of my django model. How can I update the existing records in my database with this list?

Models.py file

class bug(models.Model):
.......
.......
status = models.CharField(max_length=25, choices=status_choice, default="Pending")
Asked By: Jin

||

Answers:

EDIT:
As it’s selected as correct answer I want to copy Hemal’s answer https://stackoverflow.com/a/74541837/2281853 to use bulk_update, it’s better for DB performance as it runs 1 query only

update_objects = []
for update_item in stat:
    update_objects.append(bug(**update_item))

bug.objects.bulk_update(update_objects, [update_field in stat[0].keys() if update_field != 'id'])

Original answer:

for update_item in stat:
    bug_id = update_item.pop('id')
    bug.objects.filter(id=bug_id).update(**update_item)

With this code, you can update any data in your list not limited to status as long as the columns are defined in your model.

Answered By: Đào Minh Hạt

You can do bulk_update

update_obj = []
for item in stat:
    update_obj.append(bug(id=item['id'], status=item['status']))
 
bug.objects.bulk_update(update_obj, ['status'])

Answered By: Hemal Patel