定义模型:
有一个数据表,就对应一个模型
生成数据表
1.在modles.py文件中定义模型
引入from django.db import models
模型类要集成modles.Model类
这里以班级和学生v表为例
from django.db import models
# Create your models here.
class Grades(models.Model):
gname = models.CharField(max)
gdate = models.DateField()
ggirlnum = models.IntegerField()
gboynum = models.IntegerField()
isDelete = models.BooleanField(default=False)
class Students (models.Model):
sname = models.CharField(max_length=20)
sgender = models.BooleanField(default=True)
sage = models.IntegerField()
scontend = models.CharField(max_length=20)
isDelete = models.BooleanField(default=False)
#关联外键
sgrade = models.ForeignKey("Grades")
说明:不需要定义主键,主键是在生成时自动添加。
2.生成数据表
生成迁移文件
执行 python3 manage.py makemigrations
在migrations 目录下生成一个迁移文件
执行迁移
执行python3 manage.py migrate
示例:
D:\untitled\0517\project>python3 manage.py makemigrations
Migrations for 'myApp':
myApp\migrations\0001_initial.py
- Create model Grades
- Create model Students
D:\untitled\0517\project>python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, myApp, sessions
Running migrations:
Applying myApp.0001_initial... OK
D:\untitled\0517\project>
数据库中已经存在2张表:
image.png
网友评论