模型
最后更新于:2022-04-02 02:17:26
[TOC]
## 定义模型(并新增一张表)
### 创建 APP
`django-admin startapp TestModel
`
输出的目录结构
```
HelloWorld
|-- TestModel
| |-- __init__.py
| |-- admin.py
| |-- models.py
| |-- tests.py
| `-- views.py
```
TestModel/models.py
```python
from django.db import models
# 类名代表了数据库表名
class Test(models.Model):
# 代表数据表中的字段(name)
name = models.CharField(max_length=20)
```
> 注意:若没有在主键,那么在生成文件中会自动创建主键
`settings.py`中找到`INSTALLED_APPS`这一项
```
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TestModel', # 添加此项
)
```
### 生成数据库
```
python manage.py makemigrations [TestModel]
python manage.py migrate [TestModel]
```
### 测试写入数据库
`urls.py`:
```
from django.conf.urls import *
from . import testdb
urlpatterns = [
url(r'^testdb$', testdb.testdb),
]
```
HelloWorld/HelloWorld/testdb.py
```
from django.http import HttpResponse
from TestModel.models import Test
# 数据库操作
def testdb(request):
test1 = Test(name='runoob')
test1.save()
return HttpResponse("
';
数据添加成功!
") ``` 访问 : `http://127.0.0.1:8000/testdb` 生成数据库 ### 打印sql ``` python manage.py sqlmigrate blog 0001 -0001即migrations目录生成的id #输出 CREATE TABLE "blog_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(32) NOT NULL, "content" text NULL); ``` ### 更新字段并同步数据库 TestModel/models.py ``` from django.db import models #类名代表了数据库表名 class Test(models.Model): # 代表数据表中的字段(name) name = models.CharField(max_length=20) age = models.IntegerField(default=0) # 新增 ``` 执行 ``` python manage.py makemigrations [TestModel] python manage.py migrate [TestModel] ```