Author: Xu FC
Django: 3.0.2
Python: 3.7.0
创建 Table
- 在 APP 中的
models.py
添加class
from django.db import models
class product_table(models.Model):
product_name = models.CharField(max_length=20, editable=True)
product_description = models.TextField(null=True)
- 同步数据库
python3 manage.py makemigrations
python3 manage.py migrate
- 查看 Table
MariaDB [TestManager]> show tables;
+----------------------------+
| Tables_in_TestManager |
+----------------------------+
| Manage0_product_table |
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
11 rows in set (0.001 sec)
- 查看表结构
MariaDB [TestManager]> desc Manage0_product_table;
+---------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| product_name | varchar(20) | NO | | NULL | |
| product_description | longtext | YES | | NULL | |
+---------------------+-------------+------+-----+---------+----------------+
3 rows in set (0.009 sec)
- 通过 django 提供的 API 插入和查询数据
➜ MProject python3 manage.py shell
>>> from Manage0.models import verified
>>> verified.objects.create(bugID='83128', product='ASF', version='1.0.2', tester='lihw', pm='xufc', ad
d_date='2020-01-19')
<verified: 83128>
>>> verified.objects.all()
<QuerySet [<verified: 84405>, <verified: 84732>, <verified: 83128>]>
>>>
删除 Table
- 将要删除的 table 对应的
class
删掉或者注释掉 - 同步数据库
python3 manage.py makemigrations
python3 manage.py migrate
问题解决
问题:不小心先删掉了数据库中的表
- 不小心先删掉了数据库中的表
- 解决办法:
- 注释掉相应的代码;
- 伪同步数据库
python3 manage.py makemigrations
python3 manage.py migrate --fake
问题:django.db.utils.ProgrammingError: (1146, "xx doesn't exist")
django.db.utils.ProgrammingError: (1146, "Table 'TestManager.django_content_type' doesn't exist")
- 解决办法:
- 删除 APP 目录下 migrations 目录下的除
__init__.py
的所有文件; - 删除数据库中
django_migrations
数据表; - 重新同步
- 删除 APP 目录下 migrations 目录下的除
python3 manage.py makemigrations
python3 manage.py migrate