Python Django | 教程 | 6.数据模型类
数据模型类:概念与说明
在前面的Django内容中,讲到了通过python manage.py startapp xxx,可以给一个Django项目创建一个新的应用。
而每个Django的应用中,都包含一个名为models.py的文件,该文件就是应用的数据模型类,它用于定义当前应用的数据结构;该文件可以为空,但是不建议删除。
一般情况下,开发一个应用,会从编写数据模型类开始。
而这个数据模型类与数据库中的数据表,具有对应关系。
在本文中,将详细的介绍Django中的models.py文件,也就是数据模型类。
为了方便理解,我画了一张图:

从上图的层级关系中可以看到:
- Django项目中可能会有很多个Django应用,每个应用中都会包含models.py的数据模型类
- 而所有的数据模型类,都继承自django.db.models.Model
- 该继承关系在数据模型类(models.py)中,通过创建class的时候继承【django.db.models.Models】命令得以体现
数据模型类:1. 编写
在继续讲解之前,先看一段样例代码:models.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from django.db import models # Create your models here. from django.contrib.auth.models import User from django.utils import timezone class Posts(models.Model): # 列 /属性 title = models.CharField(max_length=300) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) # 元类 class Meta: ordering = ("-publish",) def __str__(self): return self.title |
根据前面的图理解:
- 对应的数据库的表名:Posts
- 该表包含四列,分别是:title / author / body / publish
- 该表的数据排序方式:根据publish倒序
- 返回给Django视图的字段是:title
数据模型类:2. 将应用注册到Django项目
如果没有将数据模型类所在的应用注册到Django中,那么在使用数据模型类生成SQL语句的时候,会提示:没有任何更改(No changes detected)
1 2 3 4 |
(venv) G:\PyCharm_data\django_datacenter>python manage.py makemigrations No changes detected (venv) G:\PyCharm_data\django_datacenter> |
注册应用,在Django项目的配置文件settings.py中设置:
1 2 3 4 5 6 7 8 9 10 11 |
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] |
数据模型类:2. 生成SQL语句
1 2 3 4 5 6 7 8 9 |
(venv) G:\PyCharm_data\django_datacenter>python -V Python 3.7.9 (venv) G:\PyCharm_data\django_datacenter>python manage.py makemigrations Migrations for 'blog': blog\migrations\0001_initial.py - Create model Posts (venv) G:\PyCharm_data\django_datacenter> |
可以看到,这时候,就生成了内容。
查看一下:0001_initial.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# Generated by Django 3.2.4 on 2021-06-17 09:17 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Posts', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=300)), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-publish',), }, ), ] |
用命令查看一下:
1 2 3 4 5 6 7 8 9 |
(venv) G:\PyCharm_data\django_datacenter>python manage.py sqlmigrate blog 0001 -- -- Create model Posts -- CREATE TABLE `blog_posts` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(300) NOT NULL, `body` longtext NOT NULL, `publish` datetime(6) NOT NULL, `author_id` integer NOT NU LL); ALTER TABLE `blog_posts` ADD CONSTRAINT `blog_posts_author_id_6f561d00_fk_auth_user_id` FOREIGN KEY (`author_id`) REFERENCES `auth_user` (`id`); (venv) G:\PyCharm_data\django_datacenter> |
可以看到:
- 创建的表名为:应用名_类名
- 列名就是数据模型类中的具体的类的属性(变量)名称
数据模型类:3. 写入数据库
查看数据库:
1 2 3 4 5 6 |
MariaDB [(none)]> use django_db; Database changed MariaDB [django_db]> show tables; Empty set (0.000 sec) MariaDB [django_db]> |
执行写入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
(venv) G:\PyCharm_data\django_datacenter>python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you a ctivate it. See: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying blog.0001_initial... OK Applying sessions.0001_initial... OK (venv) G:\PyCharm_data\django_datacenter> |
再次查看数据库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
MariaDB [django_db]> show tables; +----------------------------+ | Tables_in_django_db | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | blog_posts | | django_admin_log | | django_content_type | | django_migrations | | django_session | +----------------------------+ 11 rows in set (0.000 sec) MariaDB [django_db]> MariaDB [django_db]> desc blog_posts; +-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | id | bigint(20) | NO | PRI | NULL | auto_increment | | title | varchar(300) | NO | | NULL | | | body | longtext | NO | | NULL | | | publish | datetime(6) | NO | | NULL | | | author_id | int(11) | NO | MUL | NULL | | +-----------+--------------+------+-----+---------+----------------+ 5 rows in set (0.002 sec) MariaDB [django_db]> |
可以看到,确实按照数据模型类的定义,创建了一张数据表。
1 thought on “Python Django | 教程 | 6.数据模型类”