1.Django模型单表
models.py:
from django.db import models
# 创建模型类
class PersonModel(models.Model):
name = models.CharField(max_length=20,unique=True)
age = models.IntegerField(default=18)
# 表名
class Meta:
db_table = "tb_person"
def __str__(self):
return f'id:{self.id}-name:{self.name}-age:{self.age}'
def __repr__(self):
return f'id:{self.id}-name:{self.name}-age:{self.age}'
views.py:
import math
from django.db.models import Max, Min, Sum, Avg, Count
from django.shortcuts import render, HttpResponse
from django.core.paginator import Paginator
# 导入models
from App.models import *
# 创建视图函数
# 添加
def add(request):
# 方式一
# try:
# user = PersonModel()
# user.name = "张三"
# user.age = 33
# user.save()
# except Exception as e:
# return HttpResponse("add fail!")
# return HttpResponse("add success!")
# 方式二
# try:
# user = PersonModel(name="李四",age="44")
# user.save()
# except Exception as e:
# return HttpResponse("add fail!")
# return HttpResponse("add success!")
# 方式三
# try:
# PersonModel.objects.create(name='王五',age=55)
# except Exception as e:
# return HttpResponse("add fail!")
# return HttpResponse("add success!")
# 方式四
# try:
# ret = PersonModel.objects.get_or_create(name='赵六', age=66)
# print(ret) # (<PersonModel: PersonModel object (4)>, True)
# except Exception as e:
# return HttpResponse("add fail!")
p = PersonModel.objects
for i in range(6, 51):
p.create(name=f'吴{i}范', age=i)
return HttpResponse("add success!")
# 删除
def delete(request):
try:
# person = PersonModel.objects.first() # 删除第一条数据
# person.delete()
PersonModel.objects.filter(age__gt=55).delete() # age > 55的数据
except Exception as e:
return HttpResponse("删除失败!")
return HttpResponse("删除成功!")
# 修改
def update(request):
try:
# 修改一条数据
p = PersonModel.objects.first()
p.age = 666
p.save(update_fields=['age']) # 修改指定的字段
# 修改多条数据
# PersonModel.objects.all().update(age = 100)
except Exception as e:
return HttpResponse('修改失败!')
return HttpResponse('修改成功!')
# 查询
def get(request):
# 查询单个
# p = PersonModel.objects.get(id = 2)
# print(p,type(p))
# print(p.name,p.age)
# p = PersonModel.objects.get(age=666)
# print(p.name,p.age)
# p = PersonModel.objects.first()
# print(p.name,p.age)
# p = PersonModel.objects.last()
# print(p.name,p.age)
# 查询全部
# p = PersonModel.objects.all()
# print(p,type(p))
# for item in p:
# print(item.name,item.age)
# filter
# p = PersonModel.objects.filter()
# print(p,type(p))
# for i in p:
# print(i.name,i.age)
# p = PersonModel.objects.filter(name='王八')
# p = PersonModel.objects.filter(age__gt=200)
# p = PersonModel.objects.filter(age__gte=200)
# p = PersonModel.objects.filter(age__lt=200)
# p = PersonModel.objects.filter(age__lte=200)
# p = PersonModel.objects.filter(age__range=[200,400])
# p = PersonModel.objects.filter(age__in=[800,300,666,777])
# p = PersonModel.objects.exclude(age__in=[200,400,880])
# p = PersonModel.objects.filter(name__contains='王')
# p = PersonModel.objects.filter(name__startswith='马')
# p = PersonModel.objects.filter(name__endswith='六')
# p = PersonModel.objects.filter(name__regex='^马')
# p = PersonModel.objects.filter(name__regex='奇$')
# p = PersonModel.objects.filter(age__='马')
# p = PersonModel.objects.filter()
# print(p.count())
# p = p.values('name','age')
# print(p)
# 聚合函数 : max,min,sum
# result = PersonModel.objects.aggregate(Max('age')) # 最大值
# result = PersonModel.objects.aggregate(Min('age')) # 最小值
# result = PersonModel.objects.aggregate(Avg('age')) # 平均值
# result = PersonModel.objects.aggregate(Count('age')) # 条数
# result = PersonModel.objects.aggregate(Sum('age')) # 求和
# print(result)
# 排序
# p = PersonModel.objects.order_by('age') # 按age升序
# p = PersonModel.objects.order_by('age','-id') # 按age升序,然后在age相同时再按id降序
# p = PersonModel.objects.order_by('-age') # 降序
# print(p)
return HttpResponse("查询成功")
# 分页查询
def paginate(request, page=1):
# page 页码
# per_page 页数
per_page = 10
persons = PersonModel.objects.all()
total = persons.count() # 总数量
total_page = math.ceil(total / per_page) # 总页数
pages = range(1, total_page + 1) # 页码列表
persons = persons[(page - 1) * per_page:page * per_page]
data = {'persons': persons, 'pages': pages}
return render(request, 'paginate.html', data)
# 分页器查询
def paginate2(request, page=1):
per_page = 10
all_data = PersonModel.objects.all()
persons = Paginator(all_data, per_page) # 分页器分页
pages = persons.page_range # 分页页码列表
persons = persons.page(page) # 获取第page页的数据
data = {'persons':persons,'pages':pages}
return render(request,'paginate2.html',data)
2.Django模型一对一关系
models.py:
from django.db import models
# 创建模型
# 身份证
class IDCard(models.Model):
idcard_num = models.CharField(max_length=18,unique=True)
address = models.CharField(max_length=200)
# 用户
class User(models.Model):
name = models.CharField(max_length=30,unique=True)
age = models.IntegerField(default=18)
sex = models.BooleanField(default=True)
# 一对一关系
idcard = models.OneToOneField(IDCard,on_delete=models.PROTECT)
views.py:
from django.shortcuts import render,HttpResponse
from One2One.models import *
# 创建视图函数
# 一对一的增删改和一对多的类似
# 查询
def select(request):
# 查询用户的身份证信息
user = User.objects.get(id=1)
print(user.idcard) # 对象
print(user.idcard.address,user.idcard.idcard_num)
# 查询身份证对应的用户信息
idcard = IDCard.objects.get(id=1)
print(idcard.user) # 对象
print(idcard.user.name,idcard.user.age,idcard.user.sex)
return HttpResponse('查询成功!!!')
3.Django模型一对多关系
models.py:
from django.db import models
# 创建模型
# 用户类型
class UserType(models.Model):
name = models.CharField(max_length=30)
# 用户
class User(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField(default=18)
user_type = models.ForeignKey(UserType,on_delete=models.PROTECT,null=True,related_name='users')
# on_delete = models.CASCADE 级联删除
# on_delete=models.PROTECT 保护删除
# on_delete=models.SET_DEFAULT,default=1 设置默认值的删除
# on_delete=models.SET_NULL,null=True 设置为null的删除
# related_name='users' 相当于user_set的关联名称
views.py:
from django.shortcuts import render,HttpResponse
from One2Many.models import *
# 创建视图函数
# 添加
def add(request):
# 添加用户类型UserType
# names = ['青铜','白银','黄金','砖石','大师','王者']
# for name in names:
# UserType.objects.create(name=name)
# 添加用户 方式一
# for i in range(11,30):
# User.objects.create(name=f'张三-{i}',age=i,user_type_id= i%6+1)
#
# 方式二
# for i in range(11, 30):
# User.objects.create(name=f'李四-{i}', age=100+i,user_type=UserType.objects.get(pk=i%6+1))
return HttpResponse("添加成功!")
# 删除数据
def delete(request):
#UserType.objects.filter(id=6).delete()
UserType.objects.filter(id=3).delete()
return HttpResponse("删除成功!")
# 修改数据
def update(request):
# 修改用户数据
# User.objects.filter(id=2).update(age=666)
# 修改用户类型数据
UserType.objects.filter(id=1).update(name='钻石')
return HttpResponse("修改成功!")
# 查询数据
def select(request):
# 正向查询
# user = User.objects.get(id=2)
# print(user.name,user.age,user.user_type,user.user_type_id)
# print(user.user_type.name,user.user_type.id)
# 反向查询
# uType = UserType.objects.get(id=1)
# print(uType.user_set) # 管理器对象
# print(uType.user_set.all()) # 查询集
# users = User.objects.filter(user_type=UserType.objects.get(name='钻石'))
# print(users)
# uType = UserType.objects.get(id=1)
# print(uType.users) # 管理器对象相当于user_set
# print(uType.users.all()) # 查询集
uType = UserType.objects.filter(users__age=666)
print(uType)
return HttpResponse("查询成功!")
4.Django模型多对多关系
models.py:
from django.db import models
# 创建模型
# 电影模型
class Movie(models.Model):
name = models.CharField(max_length=100)
duration = models.IntegerField(default=90)
# 用户模型
class User(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField(default=18)
# 多对多关系
movies = models.ManyToManyField(Movie)
views.py:
from django.shortcuts import render,HttpResponse
from Many2Many.models import *
# 创建视图函数
# 添加数据
def add(request):
# 添加用户数据
# for i in range(1,10):
# User.objects.create(name=f'张三{i}',age=i)
# 添加电影
# for i in range(1,10):
# Movie.objects.create(name=f'阿凡达{i}',duration=100+i)
# 添加中间表的数据
# 让张三1 收藏 阿凡达1
user = User.objects.get(name='张三1')
movie = Movie.objects.get(name='阿凡达2')
# 添加收藏
# user.movies.add(movie) # 用户收藏电影
movie.user_set.add(user) # 电影被用户收藏
return HttpResponse('添加成功!!!')
# 删除
def delete(request):
# 删除用户
# User.objects.get(id=9).delete()
# 删除电影
# Movie.objects.get(id=9).delete()
# 删除中间表
# 除了删除中间表还删除了电影表中的阿凡达3这条记录
# user = User.objects.get(name='张三1')
# user.movies.filter(name='阿凡达3').delete()
# 只删除中间表的关联记录数据
user = User.objects.get(name='张三1')
movie = Movie.objects.get(name='阿凡达4')
user.movies.remove(movie)
return HttpResponse('删除成功!!!')
# 查询
def select(request):
# 获取用户收藏的所有电影
user = User.objects.get(id=1)
print(user.movies.all())
print('-'*50)
# 获取电影被哪些用户收藏了
movie = Movie.objects.get(id=4)
print(movie.user_set.all())
return HttpResponse('查询成功!!!')