Creating objects

Open the terminal and run the following command to open the Python shell:

python manage.py shell

Then, type 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 what this code does. First, we will retrieve the user object with the username admin:

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

The get() method allows you to retrieve a single object from the database. Note that this method expects a result that matches the query. If no results are returned by the database, this method will raise a DoesNotExist exception, and if the database returns more than one result, it will raise a MultipleObjectsReturned exception. Both exceptions are attributes of the model class that the query is being performed on.

Then, we create a Post instance with a custom title, slug, and body, and we set the user we previously retrieved as the author of the post:

post = Post(title='Another post', slug='another-post', body='Post body.', author=user)
This object is in memory and is not persisted to the database.

Finally, we save the Post object to the database using the save() method:

post.save()

The preceding action performs an INSERT SQL statement behind the scenes. We have seen how to create an object in memory first and then persist it to the database, but we can also create the object and persist it into the database in a single operation using the create() method, as follows:

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

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.103.183