新建项目和应用

django-admin startproject emp_manage
django-admin startapp app

注意:记得在settings.py中注册app。

创建表结构

在models.py修改

from django.db import models


class Department(models.Model):
"""部门表"""
# id = models.BigAutoField(verbose_name="ID",primary_key=True)
title = models.CharField(verbose_name='标题', max_length=32)


class UserInfo(models.Model):
"""员工表"""
name = models.CharField(verbose_name="姓名", max_length=16)
password = models.CharField(verbose_name="密码", max_length=64)
age = models.IntegerField(verbose_name="年龄")
account = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
create_time = models.DateTimeField(verbose_name="入职时间")
gender_choices =(
(1,"男"),
(2,"女")
)
gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)
# 有约束
# - to, 与哪张表关联
# - to_field, 表中的那一列关联
# - 自动生成depart_id,自动带上id的原因是外键为id
# 1.部门被删除,级联删除
# depart = models.ForeignKey(to="Department", to_field="id",on_delete=models.CASCADE)
# 2. 部门被删除,置空
depart = models.ForeignKey(to="Department", to_field='id',null=True,blank=True,on_delete=models.SET_NULL)

生成数据库

  • 创建数据库emp_manage

  • 修改settings.py

DATABASES = {
'default':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'emp_manage', # 数据库名称
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
  • 执行命令
python manage.py makemigrations
python manage.py migrate