Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Models.py file

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading