Django update data

Prerequisites

Django shell

  • Run the command python manage.py shell open the django shell.

Django Model - Contact

my_app/models.py

from django.db import models

class Contact(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=255)
    phone = models.CharField(max_length=10, null=True)

    class Meta:
        db_table = "contact"

Add few records to database

from my_app.models import Contact

contacts = [
    {"first_name": "Johan", "last_name": "K", "email": "[email protected]"},
    {"first_name": "Johanan", "last_name": "M", "email": "[email protected]"},
    {"first_name": "Joharr", "last_name": "K", "email": "[email protected]"},
    {"first_name": "Mani", "last_name": "M", "email": "[email protected]"},
]
objects = [Contact(**d) for d in contacts]
results = Contact.objects.bulk_create(objects)

update single record - save()

  • Retrieve the record and make some changes to the fields and call save() method to udpated the record.
  • Let's look at an example.
from my_app.models import Contact

obj = Contact.objects.get(email='[email protected]')
obj.first_name = "Jerry"
obj.save()

update multiple records - bulk_update()

  • Retrive individual records and update at once.
  • use bulk_update() method to update it.
from my_app.models import Contact

obj1 = Contact.objects.get(email='[email protected]')
obj1.first_name = "Jerry"

obj2 = Contact.objects.get(email='[email protected]')
obj2.first_name = "Bingo"

updated_count = Contact.objects.bulk_update([obj1, obj2], ['first_name'])
print(updated_count)
# output: 2

update multiple records - update()

  • Update multiple records without retrieving using update()
from my_app.models import Contact

update_count = Contact.objects.filter(email='[email protected]').update(last_name="MD")
print(updated_count)
# output: 2

References