4.B] Explain the steps involved in inserting and updating data in Django models.
In Django, inserting and updating data in models is straightforward, because of Django’s Object-Relational Mapping (ORM) system. Here are the steps involved:
Inserting Data
- Create an Instance of the Model:
- First, create an instance of the model by calling the model class and passing the required keyword arguments. This step does not interact with the database but simply prepares an instance with the specified data.
p = Publisher( name='Apress', address='2855 Telegraph Ave.', city='Berkeley', state_province='CA', country='U.S.A.', website='http://www.apress.com/' )
- Save the Instance to the Database:
- To insert the record into the database, call the
save()
method on the instance. This method performs an SQLINSERT
operation if the instance is new (i.e., it doesn’t have a primary key value yet).
p.save()
- When you call
save()
for the first time, Django generates an SQLINSERT
statement like this:INSERT INTO book_publisher (name, address, city, state_province, country, website) VALUES ('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA', 'U.S.A.', 'http://www.apress.com/');
- After the
save()
method executes, Django assigns the primary key value (typically an auto-incremented ID) to theid
attribute of the instance.
print(p.id) # This will output the auto-assigned ID, e.g., 52
Updating Data
- Retrieve the Instance:
- To update an existing record, first retrieve the instance from the database. You can use Django’s querying methods like
get()
to fetch the instance you want to update.
p = Publisher.objects.get(id=52)
- Modify the Instance:
- Update the attributes of the retrieved instance with new values.
p.name = 'Apress Publishing'
- Save the Changes to the Database:
- Call the
save()
method again to update the record in the database. This time, Django performs an SQLUPDATE
operation instead of anINSERT
.
p.save()
- The
save()
method generates an SQLUPDATE
statement like this:UPDATE book_publisher SET name = 'Apress Publishing', address = '2855 Telegraph Ave.', city = 'Berkeley', state_province = 'CA', country = 'U.S.A.', website = 'http://www.apress.com' WHERE id = 52;
Summary
- Inserting Data:
- Create a model instance with the desired data.
- Call
save()
to insert the record into the database.
- Updating Data:
- Retrieve the existing model instance using query methods.
- Modify the instance attributes.
- Call
save()
to update the existing record in the database.
By following these steps, Django makes it easy to handle database operations while abstracting away the underlying SQL complexities.