Django framework (II): Design Model

1. Design model

Before we are operating database by writing sql statement, then can we not write sql statement can operate database? Of course, it is necessary to use an ORM framework.

1.1 ORM framework

Object O is, it means the object class, R is Relation, in Chinese translated into the relationship, i.e. data table in the relational database means, M is a mapping, the mapping is meant. In the ORM framework, which help us to classes and data tables a map, it allows us to corresponding data in the table will be able to operate through classes and objects. ORM framework also has a feature that can help us to automatically generate a table in the database according to our design class, eliminating the need for the process to build our own table.

django ORM framework embedded in, need not be directly oriented database programming, but the class definition model, completion of additions and deletions by the data table class and object model change search operation.

Database development using django There are three steps:

1. Define the model classes models.py

2. Migration

3. By classes and objects for data CRUD operations

Here we have an example to hold book information to tell you about the entire process of database development with Django.

1.2 to create a model

Create models in models.py under booktest, the need to inherit models.Model categories:

from django.db Import Models
 # design and model class table corresponding to the category 
# the Create your Models here Wallpaper.

# Books class 
class the BookInfo (models.Model):
     '' ' Books model class ' '' 
    # Books Name Description CharField the maximum length of a string is specified string max_length 
    BTITLE = models.CharField (= 20 is max_length )
     # Publication Date DateField Description is a date type 
    bpub_date = models.DateField ()

1.3 Migration

Migration has two steps:

1. Generate a migration file: Create a migration file table model classes generated from.

2. perform the migration: Create a table in the database according to the first step in the migration file generated.

Migrate files generated commands are as follows:

 python manage.py makemigrations

After executing the command generates a file migration, the migration file migrations will generate directory under the application booktest directory. 

We open this file, as follows:

# Generated by Django 3.0.2 on 2020-01-15 07:01

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='BookInfo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('btitle', models.CharField(max_length=20)),
                ('bpub_date', models.DateField()),
            ],
        ),
    ]

According to our model classes Django framework designed to generate a file migration, the migration file, we can see the list of fields with BookInfo class attribute name and type of each element attributes are consistent. We found one more item id, this one is the Django framework to help us automatically generated when creating a table id as the primary key column will correspond to the table, and the primary key column to grow automatically.

When performing a migration command, Django framework will help us to read migrate files automatically generates the corresponding table in the database. 

 

Django defaults sqlite3 database, the image above is db.sqlite3 Django framework to help us automatically generated database file. sqlite3 is a small database, commonly used in mobile phones, it is like mysql, we can also operate it by sql statement. 

But we generally use mysql as a case, so we need to model into mysql database table.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'bms',        # 要连接的数据库,连接前需要创建好
        'USER':'root',       # 连接数据库的用户名
        'PASSWORD':'root',       # 连接数据库的密码
        'HOST':'127.0.0.1', # 连接主机,默认本机
        'PORT':3306           # 端口 默认3306
    }
}

NAME即数据库的名字,在mysql连接前该数据库必须已经创建,而上面的sqlite数据库下的db.sqlite3则是项目自动创建 USER和PASSWORD分别是数据库的用户名和密码。设置完后,再启动我们的Django项目前,我们需要激活我们的mysql。然后,启动项目,会报错:no module named MySQLdb 。这是因为django默认你导入的驱动是MySQLdb,可是MySQLdb对于py3有很大问题,所以我们需要的驱动是PyMySQL。所以我们还需要找到项目名下的__init__,在里面写入:

import pymysql
pymysql.install_as_MySQLdb()

然后我们还要注意一个报错,报错如下:

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

MySQLclient目前只支持到python3.4,因此如果使用的更高版本的python,需要修改如下:

通过路径查找E:\pythondaima\venv\Lib\site-packages\django\db\backends\mysql\base..py。在这个路径下找到如下地方:

注释掉就OK了。 

还有就是上一章讲过的,确保配置文件中的INSTALLED_APPS中写入我们创建的app名称。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
]

删除原来生成的文件,重新运行两条命令:

python manage.py makemigrations

python manage.py migrate

我们可以看到生成的表名叫做booktest_bookinfo,booktest是应用的名字,bookinfo是模型类的名字。

我们再弄个角色类:

在booktest/models.py,定义角色类:

class RoleInfo(models.Model):
    '''角色人物模型类'''
    # 角色名
    rname = models.CharField(max_length=20)
    # 性别
    rgender = models.BooleanField()
    # 备注
    rcomment = models.CharField(max_length=100)
    # 关系属性
    rbook = models.ForeignKey('BookInfo',on_delete=models.CASCADE)

在外键值的后面加上 on_delete=models.CASCADE,因为在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错。

这里要说明的是,BookInfo类和RoleInfo类之间具有一对多的关系,这个一对多的关系应该定义在多的那个类,也就是RoleInfo类中。

在我们之后迁移生成表的时候,Django框架就会自动帮我们在图书表和角色表之间建立一个外键关系。

python manage.py makemigrations

python manage.py migrate

1.4 操作数据库

1.4.1 单表操作

完成数据表的迁移之后,下面就可以通过进入项目的shell,进行简单的API操作。如果需要退出项目,可以使用ctrl+d快捷键或输入quit()。

进入项目shell的命令:

python manage.py shell

首先引入booktest/models中的类:

from booktest.models import BookInfo,RoleInfo

查询所有图书信息:

BookInfo.objects.all()

因为当前并没有数据,所以返回空列表。

新建图书对象: 

b=BookInfo()
b.btitle="斗罗大陆"
from datetime import date
b.bpub_date=date(2008,12,14)
b.save()

再次查询所有图书信息:

BookInfo.objects.all()

查找图书信息并查看值:

b=BookInfo.objects.get(id=1)
b
b.id
b.btitle
b.bpub_date

修改图书信息:

b.bpub_date=date(2017,1,1)
b.save()
b.bpub_date

删除图书信息:

b.delete()

1.4.2 多表关联操作

对于RoleInfo可以按照上面的方式进行增删改查操作。

创建一个BookInfo对象

b=BookInfo()
b.btitle='abc'
b.bpub_date=date(2017,1,1)
b.save()

创建一个RoleInfo对象

r=RoleInfo()
r.rname='a1'
r.rgender=False
r.rcomment='he is a boy'
r.rbook=b
r.save()

图书与角色是一对多的关系,django中提供了关联的操作方式。

获得关联集合:返回当前book对象的所有role。

b.roleinfo_set.all()

Guess you like

Origin www.cnblogs.com/liuhui0308/p/12196809.html