官术网_书友最值得收藏!

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)
主站蜘蛛池模板: 青阳县| 嘉兴市| 绿春县| 濮阳县| 梓潼县| 江口县| 老河口市| 合山市| 长寿区| 兴业县| 黔西县| 兖州市| 松溪县| 兴山县| 大足县| 牙克石市| 正宁县| 丰城市| 上犹县| 方山县| 萨迦县| 神农架林区| 六安市| 海安县| 夏津县| 巴林右旗| 白沙| 荔波县| 屏边| 通河县| 东兰县| 宜良县| 基隆市| 依安县| 南昌市| 屏东县| 交城县| 东海县| 通州市| 翁源县| 赤水市|