20 Advanced Architecture Topics Daily Delivery Model Operation Review In the previous chapter, we established a model for a blog post, and then established the database tables in our corresponding through data migration. In this chapter, we will continue to talk about the operati

2025/06/1210:21:39 hotcomm 1748


0 Large Advanced Architecture Special Topics delivered to

20 Advanced Architecture Topics Daily Delivery Model Operation Review In the previous chapter, we established a model for a blog post, and then established the database tables in our corresponding through data migration. In this chapter, we will continue to talk about the operati - DayDayNews

Model Operations

Review

In the previous chapter, we established a model for a blog post, and then built our corresponding database table through data migration. In this chapter, we will continue to talk about the operation of the model. A small part of this chapter may require everyone to be a little familiar with database operations. I believe that everyone is looking at this set of introductory notes with the purpose of learning Django. I dare not show off my skills in front of all the database masters, so I will go directly to this chapter to study.

SQLite startup

The operation of database can be achieved using GUI tools, or through the command line sqlite3 db.sqlite3. We use the above command in the directory where db.sqlite3 is located to enter the db.sqlite3 database. If the SQLite environment is not configured in the local development, you can search for how to configure it yourself.

If we enter the command and see the following information, it means that the entry is successful:

 ~/DjangoProject/myblog $ sqlite3 db.sqlite3
SQLite version 3.29.0 2019-07-10 17:32:03
Enter ".help" for usage hints.
sqlite

Then we use ".tables" to view the name of the database table in the current database. Except for blog_blogarticles that we built through the BlogArticles model, the rest are database tables created by the project by default.

 ~/DjangoProject/myblog $ sqlite3 db.sqlite3
SQLite version 3.29.0 2019-07-10 17:32:03
Enter ".help" for usage hints.
sqlite.tables
auth_group blog_blogarticles
auth_group_permissions django_admin_log
auth_permission django_content_type
auth_user django_migrations
auth_user_groups django_session
auth_user_user_permissions
sqlite

Next use the pragma table_info(blog_blogararticles); command to view the structure of the blog_blogararticles table:

sqlite.header on
sqlite pragma table_info(blog_blogararticles);
cid|name |type |not|dflt_value|pk
0|id |integer |1 | |1
1|title |varchar(300)|1 | |0
2|body |text |1 | |0
3|publish |datetime |1 | |0
4|author_id|integer |1 | |0
sqlite

.header on Turn on the header to display SQLite's PRAGMA command is a special command that can be used to control various environment variables and status flags in the SQLite environment. A PRAGMA value can be read or can be set according to requirements.

We can roughly check the table structure above. cid refers to column id, name refers to column name, type refers to column type, not non-empty, value of 1 means True, dflt_value refers to default value (this column has no value, indicating setting the default value), and pk refers to primary_key primary key.

You can compare the fields and attributes specified by our data model BlogArticles in the previous chapter. Is it just so happen that we successfully transformed the data model into a database table using data migration?

Create Super Administrator

We can enter python manage.py createsuperuser to create a Django super administrator, enter the user name and password, and when prompted Superuser created successfully, the creation is successful. As follows:

 ~/DjangoProject/myblog $ python manage.py createsuperuser
Username (leave blank to use 'yuzhou_1su'): zoeu
Email address: test@testt.com
Password:
Password (again):
Superuser created successfully.

Then I type http://127.0.0.1:8000/admin/ in my browser, and I can open the following interface:

20 Advanced Architecture Topics Daily Delivery Model Operation Review In the previous chapter, we established a model for a blog post, and then established the database tables in our corresponding through data migration. In this chapter, we will continue to talk about the operati - DayDayNews

Enter the user name and password of the super administrator you just created and you can enter the system, as shown in the figure:

20 Advanced Architecture Topics Daily Delivery Model Operation Review In the previous chapter, we established a model for a blog post, and then established the database tables in our corresponding through data migration. In this chapter, we will continue to talk about the operati - DayDayNews

Groups and Users are the default user categories for Django in user management applications.In order to enable our administrator users to publish a blog, we need to add the following code in the ./blog/admin.py file:

from django.contrib import admin
# Added, introduce the BlogArticles class into the current environment
from .models import BlogArticles 12
# Register BlogArticles in admin
admin.site.register(BlogArticles)

Refresh the page, and we can get the following page:

20 Advanced Architecture Topics Daily Delivery Model Operation Review In the previous chapter, we established a model for a blog post, and then established the database tables in our corresponding through data migration. In this chapter, we will continue to talk about the operati - DayDayNews

The super administrator interface is first placed here, and we return to the model operation.

Experimental Model API

An important advantage of developing using Python is the interactive shell. After we create a data model in ./blog/models.py, Django will automatically provide the database abstract API, which is a way to quickly try and experiment with the API. Through this API we can quickly create, retrieve, modify and delete objects. For this we call it ORM (Object-Relational Mapper)

We can use the manage.py tool to load our project to start Python shell:

python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

Please pay special attention to the way we enter the shell, not directly typing python3 on the command line, although this is very similar to directly entering python instructions to call the interactive console.

The difference is that we use the manage.py tool to add the project to sys.path and load Django. This means we can import our model and other resources in the project and use it.

Let us start by importing the BlogArticles class: the following can start our operations on adding, deleting, modifying, and searching the database.

$ python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
from django.contrib.auth.models import User
from blog.models import BlogArticles
admin = User.objects.get(username="zoeu")
admin.username
'zoeu'
admin.id
1
admin.password
'pbkdf2_sha256$150000$b9j0ZKBVZSo1$l+fEIiKIaS6u1mhjMPOX1qR0xMOaemnRJIwiE2lNn60='
admin.email
'[email protected]'
type(admin)
class 'django.contrib.auth.models.User'

or above query operations on users are exactly what you defined yourself in the creation of the administrator in the previous section.

Next, we operate on the blog post. To create a new BlogArticle object, we can perform the following operations:

  1. Increase

 BlogAriticle01 = BlogArticles(title ='DjangoNotes_Day01', author=admin, body='What is Django?'); 

In order to save this object in the database, we must call the save method:

 BlogAriticle01.save

save method is used to create and update the object. Here Django creates a new object because the BlogAriticle01 instance has no id. After the first save, Django will automatically set the ID:

 BlogAriticle01.id
4

Because I have created other articles before, this id value is 4. If you follow this introductory note step by step, the id value should be 1. Of course, you can also view other properties. Here we uniformly type the command:

 BlogAriticle01.title
'DjangoNotes_Day01'
BlogAriticle01.author
User: admin
BlogAriticle01.body
'What is Django? '
BlogAriticle01.publish
datetime.datetime(2019, 9, 30, 19, 56, 58, 735676)

Each Django model has a special attribute; we call it the Model Manager. You can access this manager through the property objects, which is mainly used for database operations.For example, we can use it to directly create a new Board object:

 BlogArticle02 = BlogArticles.objects.create(title='Python', author=admin, body='Head First to Python.')
BlogArticle02.id
5
  1. Change

To update a value, we can do the following:

 BlogAriticle01.body = 'I love Django, but it's too difficult for me'
BlogAriticle01.body
'I love Django, but it's too difficult for me'

Also in order to save this changed object in the database, we must call the save method:

 BlogAriticle01.save
  1. Check

 blogs = BlogArticles.objects.all
blogs
QuerySet [BlogArticles: Python, BlogArticles: DjangoNotes_Day01, BlogArticles: right here waiting, BlogArticles: Yesterday once more, BlogArticles: You Raise me up]

The result is a QuerySet, we can regard this QuerySet as a list. Suppose we want to iterate over it and print the title of each module.

 for blog in blogs:
... print(blog.title)
...
Python
DjangoNotes_Day01
right here waiting
Yesterday once more
You Raise me up

Similarly, we can use the model's manager (Manager) to query the database and return a single object. To do this, we need to use the get method:

 BlogArticles.objects.get(id=5)
BlogArticles: Python
  1. delete

 BlogArticles.objects.get(id=5).delete
(1, {'blog.BlogArticles': 1})

deletes QuerySet again, and finds that there is no BlogArticles: Python, which indicates that the deletion is successful.

 blogs = BlogArticles.objects.all
blogs
QuerySet [BlogArticles: DjangoNotes_Day01, BlogArticles: right here waiting, BlogArticles: Yesterday once more, BlogArticles: You Raise me up]

In addition to the get method, you can also use filter to filter query id=5 and then delete it, BlogArticles.objects.filter(id=5).delete. We will introduce the filter method in the following article.

Summary

In this chapter, we first learned some simple operations about the SQLite database. Then we created the superuser module (that is, the administrator) that comes with Django and logged in. Based on the learning of these two contents, we began to experiment in the console with our API for creating blog post model.

Below are the methods and operations we learned about the model in this section, using the BlogArticles model as a reference. BlogArticles refers to the class, BlogArticles01 refers to an instance (or object) of BlogArticles

Operation Code example
Create an object without saving BlogAriticle01 = BlogArticles
Save an object (create or update) BlogAriticle01.save
Create and save an object in the database BlogArticle02 = BlogArticles.objects.create(title='...', author=..., body='...')
List all objects BlogArticles.objects.all
Get a single object through field identification BlogArticles.objects.get(id=5)
Delete a single object through field identification BlogArticles.objects.get(id=5).delete

How about it? Are readers who have learned this excited? I found that when I write these words, it is also a good opportunity to practice repeatedly, which deepens my impression of model operations. I also hope that everyone can understand these operations through more practice.

The next chapter is the part where we are going to start learning views. We will create a blog post through the administrator interface and then display our blog name in HTML.See you next chapter!

———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

hotcomm Category Latest News