Django Models
Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, Oracle.
Django provides a unified API for these databases. We can choose different databases according to our own business needs.
MySQL is the most commonly used database in web applications. In this chapter we will use MySQL as an example. You can learn more about MySQL basics through this site'sMySQL Tutorial to learn more about MySQL basics.
If you have not installed the mysql driver, you can run the following command to install it:
sudo pip3 install pymysql
Django ORM
Django models use the built-in ORM.
Object Relational Mapping (ORM) is used to achieve the conversion between data of different types of systems in object-oriented programming languages.
ORM acts as a bridge between the business logic layer and the database layer.
ORM automatically persists objects in the program to the database by using metadata that describes the mapping between objects and the database.

Benefits of using ORM:
- Improve development efficiency.
- Different databases can be switched smoothly.
Disadvantages of using ORM:
- When ORM code is converted to SQL statements, it takes some time and execution efficiency is reduced.
- Writing ORM code for a long time will reduce your ability to write SQL statements.
ORM parsing process:
- 1. ORM converts Python code into SQL statements.
- 2. SQL statements are transmitted to the database server through pymysql.
- 3. Execute the SQL statements in the database and return the results.
ORM correspondence table:

Database configuration
How Django uses the mysql database
Syntax for creating a MySQL database (ORM cannot operate at the database level, only at the data table level):
create database 数据库名称 default charset=utf8; # 防止编码问题,指定为 utf8
For example, we create a database named runoob with encoding specified as utf8:
create database runoob default charset=utf8;
We find the DATABASES configuration item in the project's settings.py file and modify its information to:
HelloWorld/HelloWorld/settings.py: file code:
DATABASES
= {
'
default
'
: {
'
ENGINE
'
:
'
django.db.backends.mysql
'
,
Database engine
'
NAME
'
:
'
runoob
'
,
Database names
'
HOST
'
:
'
127.0.0.1
'
,
Database address, local IP address 127.0.0.1
'
PORT
'
:
3306
,
port
'
USER
'
:
'
root
'
,
Database username
'
PASSWORD
'
:
'
123456
'
,
Database password
} }
If you are using Python 2.x, a Chinese comment is added here, so you need to add # - at the top of the HelloWorld/settings.py file- coding: UTF-8 --。
The above contains the database name and user information, which is the same as the corresponding database and user settings in MySQL. Based on this setting, Django connects to the corresponding database and user in MySQL.
Next, tell Django to use the pymysql module to connect to the mysql database:
Example
In the directory at the same level as settings.py, initimport the module and configure it in the .py
import
pymysql
pymysql.
install_as_MySQLdb
(
)
Define the model
Creating an APP
Django stipulates that to use models, you must create an app. We use the following command to create an app named TestModel:
django-admin startapp TestModel
The directory structure is as follows:
HelloWorld
|-- HelloWorld
|-- manage.py
...
|-- TestModel
| |-- __init__.py
| |-- admin.py
| |-- models.py
| |-- tests.py
| `-- views.py
We modify the TestModel/models.py file, with the following code:
HelloWorld/TestModel/models.py: file code:
models.py
from
django
.
db
import
models
class
Test
(
models
.
Model
)
:
name
=
models
.
CharField
(
max_length
=
20
)
The class names above represent database table names and inherit from models.Model; the fields in the class represent the fields in the data table (name), the data types are determined by CharField (equivalent to varchar) and DateField (equivalent to datetime), and the max_length parameter limits the length.
Next, find the INSTALLED_APPS item in settings.py, as follows:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TestModel', # 添加此项
)
Run in the command line:
$ python3 manage.py migrate # 创建表结构
$ python3 manage.py makemigrations TestModel # 让 Django 知道我们在我们的模型有一些变更
$ python3 manage.py migrate TestModel # 创建表结构
Once you see a few lines with "Creating table...", your data table has been created.
Creating tables ...
……
Creating table TestModel_test #我们自定义的表
……
The table name is structured as: app name_class name (for example: TestModel_test).
**Note:** Although we did not set a primary key for the table in models, Django will automatically add an id as the primary key.
Common error messages
If the following error message appears when running the above command:

The reason is that MySQLclient currently only supports up to Python 3.4, so if you are using a higher version of Python, you need to modify the following:
Use the file path in the error message to find the base.py file in the path ...site-packages\Django-2.0-py3.6.egg\django\db\backends\mysql, and comment out these two lines of code (the code is at the beginning of the file):
if version < (1, 3, 13):
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

Generally, clicking on the code file path information in the error automatically jumps to the line number in the error file, where we then comment out the line.
If the following error message appears:

We click on the code file path in the error, jump to the line number in the error file, and add the following before the line:
query = query.encode()

Database operations
Next, we add a testdb.py file in the HelloWorld directory (described below) and modify urls.py:
HelloWorld/HelloWorld/urls.py: file code:
from
django
.
urls
import
path
from
.
import
views
,
testdb
urlpatterns
=
[
path
(
'
runoob/
'
,
views
.
runoob
)
,
path
(
'
testdb/
'
,
testdb
.
testdb
)
,
]
Add data
To add data, you need to first create an object and then execute the save function, which is equivalent to INSERT in SQL:
HelloWorld/HelloWorld/testdb.py: file code:
-- coding: utf-8 --
from
django
.
http
import
HttpResponse
from
TestModel
.
models
import
Test
Database operations
def
testdb
(
request
)
:
test1
=
Test
(
name
=
'
runoob
'
)
test1
.
save
(
)
return
HttpResponse
(
"
Data added successfully!
"
)
Access the http://127.0.0.1:8000/testdb you will see the prompt that data was added successfully.
The output is as follows:

Get the data
Django provides multiple ways to get database content, as shown in the following code:
HelloWorld/HelloWorld/testdb.py: file code:
-- coding: utf-8 --
from
django
.
http
import
HttpResponse
from
TestModel
.
models
import
Test
Database operations
def
testdb
(
request
)
:
Initialization
response
=
"
"
response1
=
"
"
Use the all() of the objects model manager to get all data rows, equivalent to SELECT * FROM in SQL
listTest
=
Test
.
objects
.
all
(
)
filter is equivalent to WHERE in SQL and can set conditions to filter results
response2
=
Test
.
objects
.
filter
(
id
=
1
)
Get a single object
response3
=
Test
.
objects
.
get
(
id
=
1
)
Limit the returned data, equivalent to OFFSET 0 LIMIT 2 in SQL;
Test
.
objects
.
order_by
(
'
name
'
)
[
0
:
2
]
# Data sorting
Test
.
objects
.
order_by
(
"
id
"
)
The above methods can be chained
Test
.
objects
.
filter
(
name
=
"
runoob
"
)
.
order_by
(
"
id
"
)
Output all data
for
var
in
listTest
:
response1
+=
var
.
name
"
"
response
=
response1
return
HttpResponse
(
"
"
response
"
"
)
Update data
To modify data, you can use save() or update():
HelloWorld/HelloWorld/testdb.py: file code:
-- coding: utf-8 --
from
django
.
http
import
HttpResponse
from
TestModel
.
models
import
Test
Database operations
def
testdb
(
request
)
:
Modify the name field where id=1, then save, equivalent to UPDATE in SQL
test1
=
Test
.
objects
.
get
(
id
=
1
)
test1
.
name
=
'
'
test1
.
save
(
)
Another way
#Test.objects.filter(id=1).update(name='Google')
Modify all columns
Test.objects.all().update(name='Google')
return
HttpResponse
(
"
Modified successfully
"
)
Delete data
To delete an object in the database, you only need to call the object's delete() method:
HelloWorld/HelloWorld/testdb.py: file code:
-- coding: utf-8 --
from
django
.
http
import
HttpResponse
from
TestModel
.
models
import
Test
Database operations
def
testdb
(
request
)
:
Delete the data where id=1
test1
=
Test
.
objects
.
get
(
id
=
1
)
test1
.
delete
(
)
Another way
Test.objects.filter(id=1).delete()
Delete all data
Test.objects.all().delete()
return
HttpResponse
(
"
Deletion successful
"
)