django--model--orm--总结--“一对一”--“一对多”--“多对多”--“增删改查”
-
Models操作
类名 ---------》 数据库表名
类属性对应 ---------》数据库里的字段
类实例对象---------》 一行数据
原Student是类名理应为数据库表名,但db_table = 'student' 这个数据库重新命名
from django.db import models class Student(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20) age = models.PositiveIntegerField() gender = models.BooleanField() email = models.EmailField() class Meta(): db_table = 'student'
单表的增删改查
单表models的原码
from django.db import models class Student(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20) age = models.PositiveIntegerField() gender = models.BooleanField() email = models.EmailField() class Meta(): db_table = 'student'
----- django2增加2种方式
方法一:
models.Teacher.objects.create(tname="李老师")
方法二:
obj = models.Teacher(tname="王老师")
obj.save()
----- django3.2增加3种方式
def add_student(request): #name = "lisi" #age = 20 #gender = True #email= '123456@126.com' #方法一 # student_obj = Student(name=name,age=age,gender=gender,email=email) # student_obj.save() #方法二 #student_obj = Student.objects.create(name=name,age=age,gender=gender,email=email) #方法三 dic={"name":"zhaoliu","age":20,"gender":True,"email":"ffqeerqe@126.com"} Student.objects.create(**dic) return HttpResponse("添加成功")
----- django2查询
1、获取所有的值
obj = models.Teacher.objects.all()
print(obj)
<QuerySet [<Teacher: 张老师>, <Teacher: 张老师>, <Teacher: 李老师>, <Teacher: 王老师>]>
2、获取第一个值
obj = models.Teacher.objects.first()
print(obj)
张老师
3、获取最后一值
obj = models.Teacher.objects.last()
print(obj)
王老师
4、查询任意一个
obj = models.Teacher.objects.filter(id=3)
print(obj)
<QuerySet [<Teacher: 李老师>]>
5、查询id大于2的老师
obj = models.Teacher.objects.filter(id__gt=2)
print(obj)
<QuerySet [<Teacher: 李老师>, <Teacher: 王老师>]>
6、查询id大于2的第一个老师
obj = models.Teacher.objects.filter(id__gt=2).first()
print(obj)
----- django3.2查询2种方法
all() 返回的关联对象是QuerySet,values()返回的是值。
def select_student(request): #all()方法 student_list=Student.objects.all() for i in student_list: print("all:",i,i.name) #values()方法 student_list1=Student.objects.values() print("values",student_list1) return HttpResponse("查询成功")
----- django2修改
models.Teacher.objects.filter(id=3).update(tname="wangsi")
----- django2删除
models.Teacher.objects.filter(id=3).delete()
----- django3.2修改
def update_student(request): Student.objects.filter(id=1).update(name="nihao") return HttpResponse("更新成功")
----- django3.2删除
def delete_student(request): Student.objects.filter(id=4).delete() return HttpResponse("删除成功")
view.py
from django.shortcuts import render,HttpResponse,redirect from ormapp import models def index(request): #增加2种方法 # models.Teacher.objects.create(tname="李老师") # obj = models.Teacher(tname="王老师") # obj.save() #查询 # obj = models.Teacher.objects.all() 获取所有 # obj = models.Teacher.objects.first() 获取第一个 # obj = models.Teacher.objects.last() 获取最后一个 # obj = models.Teacher.objects.filter(id=3) 查询任意一个 # obj = models.Teacher.objects.filter(id__gt=2) 查询id大于2的老师 # obj = models.Teacher.objects.filter(id__gt=2).first() 查询id大于2的第一个老师 models.Teacher.objects.filter(id=3).update(tname="wangsi") models.Teacher.objects.filter(id=3).delete() return HttpResponse("填加成功")
models.py
from django.db import models class Teacher(models.Model): tname = models.CharField(max_length=32) def __str__(self): return self.tname class Classes(models.Model): title = models.CharField(max_length=32) ct = models.ManyToManyField("Teacher") def __str__(self): return self.name class student(models.Model): name = models.CharField(max_length=32) age = models.BooleanField(default='男') sc = models.ForeignKey(Classes,on_delete=True) """定义每个数据对象的显示信息""" def __str__(self): return self.name
urls.py
""" from django.contrib import admin from django.urls import path from ormapp import views urlpatterns = [ path('index/', views.index), ]
一对多表的增删改查(FK代指关系表中的一行数据:__跨表)
models 3种表学生,班级,课程
班级:学生 一对多
课程:学生 多对多
from django.db import models class Grades(models.Model): """ 班级 """ gno = models.IntegerField(primary_key=True,default=None) gname = models.CharField(max_length=30) class Meta(): db_table = 'grade' class Course(models.Model): """ 课程 """ cno = models.IntegerField(primary_key=True) cname = models.CharField(max_length=20) class Meta(): db_table = 'course' class Student(models.Model): """ 学生 """ sid = models.IntegerField(primary_key=True) sname = models.CharField(max_length=20) sage = models.PositiveIntegerField() sgender = models.BooleanField() semail = models.EmailField() gradesstu=models.ForeignKey(Grades,on_delete=models.CASCADE) coursestu=models.ManyToManyField(Course) class Meta(): db_table = 'student'
1、1对多增加
app01/views
#一对多操作 def add_grade(request): flag = random.randint(100,999) gname=flag grade_obj = Grades(gname=gname) grade_obj.save() return HttpResponse("班级增加成功") def add_grade_student(request): # 1.可以从班级(grade)查询出来对象,对象信息只能是一条2.可以重新创建一个班级(grade)对象.3、外键gradesstu的value值只能是一个对象 flag = random.randint(100, 999) c1 = Grades.objects.get(gno=1) print("dadadadf",c1.gno) dic = {"sname": "wangwu", "sage": flag, "sgender": False, "semail": "wangwu%s@126.com"%(flag),"gradesstu":c1} Student.objects.create(**dic) return HttpResponse("往班级增加学生成功")
数据展示
1对多查询
def select_grade_student(request): #1对多查询 #方法一 反向查询 # grade_list = Grades.objects.get(gno=1).student_set.all() # print("班级向学生反响查询1",grade_list) # 方法二 反向查询 # grade_list = Grades.objects.get(gno=1).student_set.values() # print("班级向学生反向查询2",grade_list) #方法一 正向查询 student_list = Student.objects.get(sname='zhaoliu').gradesstu print("学生向班级正向查询",student_list) return HttpResponse("查询学生成功")
1对多修改
1对多删除
多对多表的增删改查(many2many字段)
-- 一张表对一张表,可以进行多对多关联
-- 第三张表采用 models.ManyToManyField(to='User'),只有3列,是固定的,无法增加多列
-- 第三张可以增加多列,采用联合唯一, u = models.ForeignKey(to='User')
t = models.ForeignKey(to='Tag')
ctime = models.DateField()
class Meta:
unique_together = [
('u','t'),
]
数据库获取数据
--[obj,obj] .all, .filter
--[{},{}] .values
--[(),()] .values_list
select标签:
-- 单选
$().val()
$().val(2)
-- 多选
$().val()
$().val([1,2,3])