示例models.py,创建几个表:
from django.db import models
#创建表命令
#python manage.py makemigrations
#python manage.py migrate
class UserInfo(models.Model):
nid = models.AutoField(primary_key=True)#自增
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
ug = models.ForeignKey("usergroup",on_delete=models.CASCADE,null=True)
# 枚举 一成不变
color_list = (
(1,'黑色'),
(2,'蓝色')
)
color = models.IntegerField(choices=color_list)
def __str__(self):
return "%s-%s"%(self.nid,self.username)
class usergroup(models.Model):
title = models.CharField(max_length=32)
# 联合唯一索引
# class Meta:
# unique_together = (
# ('title')
# )
# index_together = (
# ('title')
# )#只建议索引
class Boy(models.Model):
name = models.CharField(max_length=32)
m = models.ManyToManyField(to='Girl',blank=True)
class Girl(models.Model):
name = models.CharField(max_length=32)
简单写一个接口测试orm数据操作:
from django.shortcuts import render,HttpResponse
from app01 import models
from django.db.models import Count,Sum,Max
# Create your views here.
def index(request):
# 新增
# models.usergroup.objects.create(title="销售部") ==》obj.save
# models.UserInfo.objects.create(username="tom",
# password="123",
# ug_id=1)
# #查询
# group_list = models.usergroup.objects.all()
# group_list = models.usergroup.objects.all().only("nid","username")
# group_list = models.usergroup.objects.all().defer('name')#排除
# #大于小于
# group_list = models.usergroup.objects.filter(id__gt=1)
# group_list = models.usergroup.objects.filter(id__lt=1)
# #删除
# models.usergroup.objects.filter(id=1).delete()
# 更新
# models.usergroup.objects.filter(id=1).update(title="研发部")
# print(group_list)
# for row in group_list:
# print(row.id,row.title)
# 正向
# result = models.UserInfo.objects.all()
# for obj in result:
# print(obj.username,obj.password,obj.ug_id,obj.ug.title)
# 反向
# result = models.usergroup.objects.all().first()
# print("部门",result.id,result.title)
# for row in result.userinfo_set.all():
# print(row.username,row.password)
# 字典
# result = models.UserInfo.objects.all().values('nid','username','ug__title')
# for row in result:
# print(row)
# #元祖
# result = models.UserInfo.objects.all().values_list('nid', 'username')
# for row in result:
# print(row)
#排序 -id从大到小 重复在按照username排序
# user_list = models.UserInfo.objects.all().order_by("-nid","username")
# print(user_list)
# 分组 v.query生成sql语句 __gt大于的意思
# v = models.UserInfo.objects.values('ug_id').annotate(xxxx=Count("nid")).filter(xxxx__gt=1)
# print(v.query)
# models.UserInfo.objects.filter(nid__gt=1)#大于
# models.UserInfo.objects.filter(nid__lt=1)#小于
# models.UserInfo.objects.filter(nid__lte=1) # 小于等于
# models.UserInfo.objects.filter(nid__gte=1) # 大于等于
# models.UserInfo.objects.filter(nid__in=[1,2,3]) #在什么里面
# models.UserInfo.objects.filter(nid__染个=[1, 2])
# models.UserInfo.objects.filter(username__startswith="xxx")
# models.UserInfo.objects.filter(username__contains="xxx")#包含
# models.UserInfo.objects.exclude(nid=1)#id不等于1
#F 跟新取到原来的值
# from django.db.models import F
# models.UserInfo.objects.all().update(password=F("password")+1)#每个密码都加1
#Q 组合搜索,构造复杂的条件
# models.UserInfo.objects.filter(nid=5,username="小红") #查询2个条件and连接
# dic = {
# "nid": 5,
# "username": "小红"
# }
# models.UserInfo.objects.filter(**dic) # 也可以接受字典
from django.db.models import Q
# models.UserInfo.objects.filter(Q(nid=5))
# models.UserInfo.objects.filter(Q(nid=5) | Q(nid=6))# 或
# models.UserInfo.objects.filter(Q(nid=5) & Q(nid=6))# and
# 对象方式 适用于多项筛选
# dic = {
# "k1": [1,2,3,4],
# "k2": [1,],
# "k3": [5,6,7]
# }
# con = Q()
# for k,v in dic.items():
# q = Q()
# q.connector = 'OR'
# for i in v:
# q.children.append(('id',i))
# con.add(q,'AND')
# models.UserInfo.objects.filter(con)
# 方法方式
# q1 = Q()
# q1.connector = 'OR'
# q1.children.append(('nid', 5))
# q1.children.append(('nid', 6))
# q1.children.append(('nid', 7))
#
# q2 = Q()
# q2.connector = 'OR'
# q2.children.append(("ug_id",1))
# q2.children.append(("ug_id", 2))
# q2.children.append(("ug_id", 3))
#
# q3 = Q()
# q3.connector = 'AND'
# q3.children.append(('id', 1))
# q3.children.append(('id', 2))
# q2.add(q3,'OR')
#
# con = Q()
# con.add(q1,'AND')
# con.add(q2,'AND')
# con = (nid = 5 or nid = 6 or nid = 7 or(id=1 and id=2)) and(ug_id=1or ug_id=2 or ug_id=3)
# extra 额外的查询条件以及表的排序
# v = models.UserInfo.objects.all().extra(select={
# "n": "select count(1) from app01_usergroup"
# },select_params=[],#select 此处 from 表
# where=["id=5","username=%s"],
# params=["小红"],# select * from 表 where 此处
# tables='',#select * from 表,此处
# order_by=None# select * from 表 order by此处
# )
# for obj in v:
# print(obj.username,obj.nid,obj.n)
# 写原生sql语句
# from django.db import connection,connections
# cursor = connection.cursor()
# cursor = connections["default"].cuirsor()
# cursor.execute("sql语句",[])
# row = cursor.fetchone()
# row = cursor.fetchall()
# models.UserInfo.objects.all().using('db2')#连接db2数据库
# res = models.UserInfo.objects.aggregate(k=Count('ug_id',distinct=True),n=Count('nid'))#distinct=True去重
# print(res)#{'k': 4, 'n': 5}
#批量插入
# objs = {
# models.UserInfo(name='r22')
# }
# models.UserInfo.objects.bulk_create(objs,10)#一次上交10个数据,最多别超过999
#get_or_create如果不存在就创建,存在就获取
#updata_or_create如果不存在就创建,存在就更新
#first第一个数据
#last#最后一个数据
#exists 是否存在
#根据主键进行查询
# models.UserInfo.objects.filter(nid__in=[1,2,3])
# models.UserInfo.objects.in_bulk([1,2,3])
#第三种查询 models.UserInfo.objects.raw()
#性能 外键连表 查询主动做连表
# q = models.UserInfo.objects.all().select_related('ug')
# for row in q:
# print(row.username,row.ug.title)
# 不做连表,做多次查询
# q = models.UserInfo.objects.all().prefetch_related('ug')
# for row in q:
# print(row.nid,row.ug.title)
#==============多对多=============================
"""
obj = models.Boy.filter(id=1).first()
增加 m是ManyToManyField字段名
obj.m.add(2)
obj.m.add(2,4)
obj.m.add(*[1,])
删除
obj.m.remove(1)
obj.m.remove(2,3)
obj.m.remove(*[1,])
更新
obj.m.set([1,])#重置
获取
obj.m.all()[Girl对象]
obj.m.filter(name='xxxx')#筛选
清空
obj.m.clear
反向
obj = models.Girl.objects.filter(name='xxx').first()
v = obj.boy_set.all()
"""
return HttpResponse("***")
这里简要的写了,具体不懂的可以详细查某一个用法!