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

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? file

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

>Solution :

As it’s selected as correct answer I want to copy Hemal’s answer to use bulk_update, it’s better for DB performance as it runs 1 query only

update_objects = []
for update_item in stat:

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')

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.

Leave a Reply