1. 问题引入
通过【Django入门】——Django中通过模型类实现数据表基本操作我们知道,通过模型类迁移生成的数据表,其默认名称为应用名_模型类名小写
。有时候我们可能希望在通过模型类迁移生成数据表的同时指定其名称。
2. 解决方案
解决上述问题的方式为:
- 在模型类中定义一个名为
Meta
的元类; - 在该类中定义一个名为
db_table
的类属性; - 为
db_table
指定一个字符串,此即为通过模型类迁移后生成的数据表名称。
下面以【Django入门】——通过模型类查询MySQL数据库基本操作中的BookInfo
模型类为例。
首先,修改BookInfo
类:
from django.db import models
# Create your models here.
class BookInfo(models.Model):
"""图书模型类"""
book_title = models.CharField(max_length=20) # 图书名称
book_pub_date = models.DateField() # 出版日期
book_read = models.IntegerField(default=0) # 阅读量,默认为0
book_comment = models.IntegerField(default=0) # 评论量,默认为0
is_delete = models.BooleanField(default=False) # 软删除标记,默认不删除
class Meta:
db_table = 'bookinfo' # 指定模型类对应的表名
然后,通过模型类重新迁移生成数据表:
$ python manage.py makemigrations
Migrations for 'booktest':
booktest/migrations/0003_auto_20200730_2120.py
- Rename table for bookinfo to bookinfo
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, booktest, contenttypes, sessions
Running migrations:
Applying booktest.0003_auto_20200730_2120... OK
最后,通过连接MySQL数据库可知的确改变数据表的名称:
mysql> use db4_test3;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_db4_test3 |
+----------------------------+
......
| bookinfo |
| booktest_areainfo |
| booktest_heroinfo |
......
+----------------------------+
13 rows in set (0.00 sec)
mysql> select * from bookinfo;
+----+-----------------+---------------+-----------+--------------+-----------+
| id | book_title | book_pub_date | book_read | book_comment | is_delete |
+----+-----------------+---------------+-----------+--------------+-----------+
| 1 | 射雕英雄传 | 1980-05-01 | 12 | 34 | 0 |
| 2 | 天龙八部 | 1986-07-24 | 36 | 40 | 0 |
| 3 | 笑傲江湖 | 1995-12-24 | 20 | 80 | 0 |
| 4 | 雪山飞狐 | 1987-11-11 | 58 | 24 | 0 |
+----+-----------------+---------------+-----------+--------------+-----------+
4 rows in set (0.00 sec)