1、model.py要设置一多得模型from django.db import models
# Create your models here.
# 1对多
# 用户类型和用户之间 用户:1:N
# 一个用户只属于 一个用户类型
# 用户类型
class userType(models.Model):
name = models.CharField(max_length=30)
class Meta:
# 定义表名
db_table = 'tb_userType'
# 用户表
class User(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField(default=18)
# 定义外键关联
userType = models.ForeignKey(userType, on_delete=models.CASCADE) # models.CASCADE是级联删除
class Meta:
# 定义表名
db_table = 'tb_user'
其中这个外键关联 后续给值得时候 1.他不能给用户类型里面没有id 2.他不能给空 空得是增补了User数据得
2.view.py书写视图函数from django.http import HttpResponse
from django.shortcuts import render
from app2.models import *
import random
from django.db import connection
def add_user(request):
# 重置UserType的AUTO_INCREMENT值
# with connection.cursor() as cursor:
# cursor.execute("ALTER TABLE tb_usertype AUTO_INCREMENT = 1;")
userTypes = ['青铜', '白银', '黄金', '钻石', '王者']
for nameType in userTypes:
userType.objects.create(name=nameType)
for i in range(10, 30):
# print(random.randint(1, 5))
User.objects.create(name=f'张三-{i}', age=i, userType_id=random.randint(1, 5))
return HttpResponse("添加成功")
3.增加urls.py路由from django.urls import path, include
from app2.views import *
urlpatterns = [
path('index/', index),
path('add_user/', add_user)
]
|