- Django 2 by Example
- Antonio Melé
- 260字
- 2021-06-25 21:19:00
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)
- RCNP實(shí)驗(yàn)指南:構(gòu)建高級的路由互聯(lián)網(wǎng)絡(luò)(BARI)
- 社交電商運(yùn)營策略、技巧與實(shí)操
- TCP/IP入門經(jīng)典(第5版)
- 大話社交網(wǎng)絡(luò)
- 數(shù)字通信同步技術(shù)的MATLAB與FPGA實(shí)現(xiàn):Altera/Verilog版(第2版)
- Getting Started with Grunt:The JavaScript Task Runner
- Building Web Applications with ArcGIS
- Working with Legacy Systems
- 面向5G-Advanced的關(guān)鍵技術(shù)
- 通信十年:擁抱互聯(lián)網(wǎng)
- 5G技術(shù)與標(biāo)準(zhǔn)
- Implementing NetScaler VPX?
- 云計(jì)算技術(shù)與標(biāo)準(zhǔn)化
- 中國互聯(lián)網(wǎng)發(fā)展報(bào)告2021
- 計(jì)算機(jī)通信網(wǎng)絡(luò)安全