Now that you know how to use the get() and all() functions of the database object manager, it is worth discussing how to modify objects that already exist in the database. The two most common functions that you will use are save() and delete(). The save() and delete() functions are part of the database-abstraction API and are accessible through each object in the model.
Earlier in this hour, we used the save() function to create a new object in the database. The save() function can also be used to update objects that exist in the database. When you retrieve an object from the database and modify it, those modifications exist only in the instance of the object in your Python code, not in the database. To update the database with the new values, use the save() function on the object. The following code snippet shows an example of updating an existing object:
from iFriends.People.models import Person from datetime import datetime p = Person.objects.get(name='King Arthur') p.birthday = datetime(934, 8, 3) p.save()
Watch Out!
If you modify an object's primary key and then use the save() function, the original object with that key is not modified in the database. Either a new object is created, because the new key doesn't exist in the database yet, or the object that does have that key is updated with the new values. This can be useful to quickly clone objects in the database.
The delete() function is used to delete objects that already exist in the database. All you have to do is retrieve the object from the database and then use the delete() function on the object, and it is deleted from the database. The following code snippet shows an example of deleting objects from the database:
from iFriends.People.models import Person p = Person.objects.get(name='Brad Dayley') p.delete()
By the Way
The delete() function also works on a QuerySet. This can be useful to delete several objects at the same time. For example, the following code deletes all the Blog objects:
from iFriends.People.models import Blog Blog.objects.all().delete()