A record can be updated, by retrieving the record, making changes to it and then calling the save()
method on it. For example, say you want to change the first_name
and last_name
of a row, you can do it in the following way :
person = Person.objects.get(id=1)
person.first_name = 'ED'
person.last_name = 'KOOL'
person.save()
In this way, you can easily change and update the entires of a single record in the database. A particular object can be retrieved by using the get()
method and then, the field values should be updated and finally the save()
method should be called in order to update the row in the database.
The save()
method performs an update operation only if the object already exists in the database. If you attempt to call save()
on a new object (one that has not been saved to the database yet), it will insert a new row into the database.
person = Person(first_name = 'Joshua', last_name = 'Forbes', birth_date = '1945-10-11')
person.save()
Now since, the save() method is called on a new object and it doesn't exist in the database, a new row will be created in the database.
Using the vars()
function, you can print the person object in the form of a dictionary.
vars(person)