Django Blog #11: Creating and Updating Objects

by Alex
Django Blog #11: Creating and Updating Objects
Now that you have a full-fledged administrative site to manage content from your blog, it’s time to learn how to retrieve information from the database and interact with it. Django has a powerful built-in API for creating, retrieving, updating, and deleting objects. Django’s ORM (object-relational mapping) tool is compatible with MySQL, PostgreSQL, SQLite, and Oracle. You can define your project’s database in the DATABASES setting in your project’s settings.py file. Django knows how to work with multiple databases simultaneously, and you can create routers to create your own routing schemes.
Once you’ve created your data models, Django provides a free API to interact with them. Here’s a link to information about it in the official documentation https://docs.djangoproject.com/en/2.0/ref/models/.

Creating Objects

Open the command line and type the following command to open a Python shell:

python manage.py shell

Try entering the following lines:

>>> from django.contrib.auth.models import User 
>>> from blog.models import Post 
>>> user = User.objects.get(username='admin') 
>>> post = Post(title='Another post', slug='another-post', body='Post body.', author=user) 
>>> post.save()

Let’s analyze in order what this code does. First, we need to get the user object whose username is admin.

user = User.objects.get(username='admin')

The get() method retrieves a single object from the database. It expects a result that matches the query. If the database does not return a result, the method will return a DoesNotExist exception, and if it returns multiple objects, it will return a MultipleObjectsReturned exception. Both exceptions are attributes of the model class to which the query was directed. Then an instance of Post is created with the name, link text and body. The user added in the previous step will be the author of the post:

post = Post(title='Another post', 
	    slug='another-post', 
	    body='post body.', 
	    author=user)

This object is stored in memory and is not represented in the database.

Next, the Post object is saved using the save() method:

post.save()

The previous action is responsible for the INSERT expression in SQL. You already know how to first create an object in memory and then move it to the database, but this can also be done with a single operation: create():

Post.objects.create(title='One more post', 
		    slug='one-more-post', 
		    body='post body.', 
		    author=user)

Update Objects

Try changing the name of the post and save the object again:

>>> post.title = 'New title ' 
>>> post.save()

This time the save( ) method will execute the UPDATE statement in SQL.

The changes made will not be saved in the database until the save()

method is called.

Related Posts

LEAVE A COMMENT