Built-in ORM support is built in Django framework, without a framework like Spring MVC, Struct2, and so on.

Configure database connectio &

A framework has been built into support for mainstream databases and writes the database that needs to be used to the DATABASES dictionary of the project profile.

By default, django uses the sqlite database.
A database file db.sqlite3 is created in the project directory while the project is created and the corresponding default database configuration is generated, as follows:

# file: [项目名称]/


 'default': {

 'ENGINE': 'django.db.backends.sqlite3',

 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),



Use other databases to modify the contents of the DATABASES dictionary, different database configuration fields.

As an example of MySQL, the configuration should be written:

# file: [项目名称]/


 'default': {

 'ENGINE': 'django.db.backends.mysql',

 'NAME': '连接的数据库名称',

 'USER': '数据库账户名称',

 'PASSWORD': '数据库账户对应密码',

 'host': '主机地址',

 'port': 3306 # mysql数据库默认端口为3306



For the MySQL database, only the paramete & in the DATABASES list are properly configured and the database connection isn't completed immediately, and the MySQL database driver is I & talled, otherwise the following error output occu & when the project starts:

ImportError: No module named 'MySQLdb'

Missing MySQLdb module cannot connect to MySQL database.

Using Python2 to install mysql-python packages.
A mysql-python package isn't migrated to Python3, and it's recommended that the mysqlclient package be installed as a MySQL database driver for Python3.

I & tall the MySQL database driver using the pip package manager:

$ pip install mysql-python //for Python2

$ pip install mysqlclient //for Python3

A series of directives are provided in the project management script for database operatio &:

  • flush clears data from the database
  • dumpdata outputs the contents of the database in the specified format
  • Log on to the interface of the specified database in the configuration ( if the database supports )
  • Database for inspectdb scan configuration, export tables in the database as django model code
  • A migrate performs migration operations that truly implement changes to makemigrations instructions to the database.
  • makemigrations commits model changes, creates a migration operation, but doesn't synchronize to the database

For a newly created django project, you should use the migrate directive of the administrative script to perform data migration after the database is configured.
First execution of the migrate instruction will create a list of projects needed in the configured database, without these tables, some of the functions ( Session, site management, and so on ) won't run properly.

Define model

In Django, the model definition is generally written in the file in the app directory:

  • should inherit from class, a model class generally corresponds to a table in the database.
  • field is a subclass of django.db.models.Field, with membe & of the model class that correspond to fields in a database table ( column ).

Depending on the field of the data table, you select the correct field type for the field in the model class, as an example of MySQL, and the common fields correspond to the type.

MySQL Django
INT IntegerField
CHAR CharField
Float, double FloatField
DECIMAL DecimalField
DATE DateField
DATETIME DateTimeField
TIME TimeField
BLOB BinaryField
TEXT TextField

Assume that there's a mysql table with the following structure:

CREATE TABLE `TestTable` (

 `Index` int(4) NOT NULL DEFAULT '0',

 `Name` varchar(48) NOT NULL DEFAULT '',

 PRIMARY KEY (`Index`)


In the django framework, the model class for the table can be written:

# file: [应用名称]/

from django.db import models

class TestTable(models.Model):

 index = models.IntegerField(primary_key = True, db_column = "Index") # primary_key用于标识主键

 name = models.CharField(max_length = 48, db_column = 'Name') # max_length用于设定最大字串长度

 class Meta:

 db_table = "TestTable"

 managed = False # managed成员设为False则该模型不由django管理(django不会为其自动生成数据库表)

By default, the name of the class name in the model class, member name, and table name in the database table, the relation of the field name 数据库表名/字段名 = App名 + 下划线 + 模型类名/成员名 .
For many times, the name of the table name generated by django defaults doesn't conform to the project naming specification, such as the TestTable table by default, named [AppName]_TestTable, which you can manually specify the corresponding table fields for the model class and class membe &:

  • For the Meta, specify the Meta class member db_table to set the database table name associated with the model class by customizing the class.
  • For the field name, specify the database field name associated with the class member by specifying the parameter content when creating the field.

Database operation

Each model has at least one manager, with the manager, and the operand data.
The default manager name is objects, which needs to be asked by model class access, and cannot be accessed through the model class instance.


For the data in the model, we can get the query set from the manager, and obtain the data from the database set.

The basic syntax for queries is as follows:

模型类名.objects.all() # 获取包含所有对象的查询集
模型类名.objects.filter(**kwargs) # 获取一个满足参数的查询集
模型类名.objects.exclude(**kwargs) # 获取一个不满足参数的查询集
模型类名.objects.order_by(*field_names) # 获取以指定字段为参数排序的结果集
模型类名.objects.get(**kwargs) # 获取一个单一的查询对象(单行记录)

The type of query set is QuerySet, supports index access, and can perform operation on it.

Model query operatio & ( filter(),exclude(), etc. ) in django have the following characteristics:

  • The result returned by the query function is still a query set, so the query function can be invoked continuously, and the filter.
  • Each query set that's called by the query function is, and isn't associated with the previous query set.
  • The query set is, and the query will be executed only if you need to evaluate it.

For a query set, you can iterate through the TestTable table in the previous table, and print all the data in the table:

for object in TestTable.objects.all():
print("Index:" + object.index +" Name:" +


I & ert data into the database, there are two ways:

  • A create() member method in the manager/query set.
  • Building a model class instance with new data, after calling the save() member method.

In the previous TestTable table, add a record:

# uses the create ( ) method
A # adds a row field index to 100, and the field name is testinsert1.
Testtable. Object. Create ( index = 100, name ="testinsert1").

# uses the save ( ) method
A # adds a row field index to 200, and the field name is testinsert2.
Insertitem = testtable ( index = 200, name = 'testinsert2 ')
Insertitem. Save ( ).


Modifying existing fields requires the following steps:

  • Get a row of records by using the get() member method of the manager.
  • Recall that the member field changes to the desired content.
  • Execute save() method to save changes.

In the previous TestTable table, modify the existing records:

# 修改index为100的记录,将其name字段修改为"TestAlter"
alterItem = TestTable.objects.get(index = 0) = 'TestAlter'

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs