Creating and updating records using Django’s database API.

In this article I’ll go over a few methods in Django’s Database API for creating, retrieving and updating objects. I’ll discuss

  • save()
  • create()
  • get()
  • get_or_create()
  • update()
  • update_or_create()

Creating objects

save() is used to commit changes to a database. To create a Person object using save() you would do:

>>> p1 = Person(first_name="Vuyisile", last_name="Ndlovu")
>>> # Invoke the save() method to create the record
>>> p1.save()

save() can also be used to update records:

>>> p1.title="Benevolent Dictator"
>>> # Invoke save() to update the record
>>> p1.save()

Using create()

Django also offers a convenient way to create and save objects in one step using create():

>>> p1 = Person.objects.create(first_name="Vuyisile", last_name="Ndlovu", title="Benevolent Dictator")
>>>

Retrieving objects

To retrieve a single record, use get():

>>> person_obj = Person.objects.get(name="Vuyisile")
>>> 

get() retrieves the object that matches the given keyword parameters. The SQL equivalent of the statement above is:

SELECT ... WHERE name = "Vuyisile";

Something you may want to do is to lookup an object or create it if it doesn’t exist:

try:
    person_obj = Person.objects.get(name="Vuyisile", last_name="Ndlovu")
except Person.DoesNotExist:
    person_obj = Person(name="Vuyisile", last_name="Ndlovu")
    person_obj.save()

Django has a built in convenience method that combines get() and create() calls to retrieve or create an object if necessary. The method is called get_or_create(). Unlike get(), get_or_create() returns a pair of results; a retrieved or newly created object, and a Boolean indicating whether the object was created:

>>> person_obj, created = Person.get_or_create(name="Vuyisile", last_name="Ndlovu")
>>>

Updating Records

Django has an update() method that performs an SQL update query on a specified field. It is similar to the save() method discussed above. Unlike save() however, update() performs an update in a single operation that helps prevent race conditions:

>>> Person.objects.filter(pk=1).update(last_name='Mthombeni')
>>>

update() can be used to update multiple records that match a filter. Here’s an example from the docs:

>>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
>>>

This would turn off comments for all blog posts published in 2010.

Another common operation when dealing with Django objects is attempting to update an object if it exists and creating it if it doesn’t. Here is an example from the Django Docs that illustrates this perfectly:

defaults = {'first_name': 'Bob'}
try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
    for key, value in defaults.items():
        setattr(obj, key, value)
    obj.save()
except Person.DoesNotExist:
    new_values = {'first_name': 'John', 'last_name': 'Lennon'}
    new_values.update(defaults)
    obj = Person(**new_values)
    obj.save()

Here, you attempt to retrieve a Person object whose first_name attribute is “John and then update that name to “Bob”. If the object doesn’t exist, a new one is created. As you can see, that’s a lot of code just to update a record. Django includes a convenience function that does the above called update_or_create()

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)

Django also allows you to add or update multiple records using the bulk_create() and bulk_update() methods that I won’t cover here.

Conclusion

You have seen the different methods offered by the Django Database API for creating and updating records. For more information on other database API methods, visit the official docs.

0 comments on “Creating and updating records using Django’s database API.Add yours →

Leave a Reply