一、django_自带的admin内存关联
效果图
(1)、创建超级django自带的admin超级用户
python manage.py createsuperuser
(2).在app,admin中创建关联用户
from django.contrib import admin
from DbLoign import models
# Register your models here
admin.site.register(models.UserInfo)
(3)在models 创建表
关键词choicesuser_type_id = models.IntegerField(choices=user_type_choices,default=1)
创建一个对应元组
class UserInfo(models.Model):
# 创建表需要用户名列,密码列,指定长度
#create UserInfo(id int auto_increment pirmary key,username char(32),password char(64))、
#Django 会默认创建自增列id
username = models.CharField(max_length=32)
password = models.CharField(max_length=60)
email = models.CharField(max_length=50,null=True)
user_type_choices =(
(1,'超级用户'),
(2,'普通用户'),
(3,'puput'),
)
user_type_id = models.IntegerField(choices=user_type_choices,default=1)
二、非内存关联法
如图
(1)models.py 配置关键字
ForeignKey('类名',to_field='字段')
Django 在帮生成关联字段的时候会在后面自动追加_id,
也就是下面代码中原本应生成user_city的字段,会自动追加成user_city_id
from django.db import models
# Create your models here.
class city(models.Model):
uid = models.IntegerField(primary_key=True)
city_name = models.CharField(max_length=20)
class useInfos(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=26)
#和第一个表中的uid字段相互关联
user_city = models.ForeignKey('city',to_field='uid')
其中city表如下:
userInfos表如下:
(2)views层如下:
主要知识点:
#想调用user_city字段给写成user_city_id
obj = models.useInfos.objects.filter(user_city_id=?)
#其中单指user_city包含了关联表中的字段,也就是city表中uid 和city_name
user_city = models.city.object.filter(uid=1).first
#models.city.object.filter(uid=1).first 中包含了city表中uid 和city_name
from django.shortcuts import render,redirect
# Create your views here.
from cmdb import models
def per_info(request):
if request.method == 'GET':
obj = models.useInfos.objects.all()
#查询所有城市返回下拉框
obj_city = models.city.objects.all()
return render(request,'info.html',{'msg':obj,'city':obj_city})
elif request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('pwd')
c = request.POST.get('city')
models.useInfos.objects.create(
username=u,
password=p,
user_city_id=c,
)
return redirect('/a/per_info')
(3)html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/a/per_info" method="post">
username<input type="text" name="username">
<br>
pwd<input type="text" name="pwd">
<br>
<select name="city">
{% for i in city %}
<option value="{{ i.uid }}">{{ i.city_name }}</option>
{% endfor %}
</select>
<input type="submit">
</form>
{% for i in msg %}
{{i.username}}-{{ i.user_city.city_name }}
<br>
{% endfor %}
</body>
</html>