django model 操作总结
使用场景
一对一:在某表中创建一行数据时,有一个单选的下拉框(下拉框中的内容被用过一次就消失了)。//两个表的数据一一对应例如:原有含10列数据的一张表保存相关信息,经过一段时间之后,10列无法满足需求,需要为原来的表再添加5列数据。一对多:当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择)。//表1的数据可以在表2里面重复出现例如:创建用户信息时候,需要选择一个用户类型【普通用户】【金牌用户】【铂金用户】等。多对多:在某表中创建一行数据是,有一个可以多选的下拉框。//表1和表2都可以在各自的表项里重复出现例如:创建用户信息,需要为用户指定多个爱好。
Customer模型:
class Customer(models.Model):
name = models.CharField(max_length=32)
qq = models.CharField(max_length=64,unique=True)
weixin = models.CharField(max_length=64,blank=True,null=True)
age = models.PositiveSmallIntegerField(blank=True,null=True)
referral_from = models.ForeignKey("Customer",related_name="my_referrals",
blank=True,null=True,verbose_name="转介绍",on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True) #auto_now_add自动增加 def __str__(self):
return self.name class Meta:
verbose_name_plural = "客户信息表"
verbose_name = "客户信息表" ----------------------------------------------------------
Enrollment模型:
class Enrollment(models.Model):
"""学员报名信息"""
customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name='entries')
class_grade = models.ForeignKey("ClassList",on_delete=models.CASCADE)
enrollment_date = models.DateField()
def __str__(self):
#return self.customer class Meta:
unique_together = ("customer","class_grade")
---------------------------------------------------------------------------
FollowUpRecord模型
class FollowUpRecord(models.Model):
customer = models.ForeignKey("Customer",on_delete=models.CASCADE)
content = models.TextField(max_length=1024)
def __str__(self):
return "%s" % self.customer
----------------------------------------------------------------------------
ClassList模型:
class ClassList(models.Model):
semester = models.PositiveSmallIntegerField(verbose_name="学期")
class_type_choices = ((0,'脱产'),(1,'周末'),(2,'网络'))
start_date = models.DateField()
end_date = models.DateField() -----------------------------------------------------------------------------------------------------------
一、单表查询
增
models.Tb1.objects.create(c1='xx', c2='oo')
增加一条数据,可以接受字典类型数据 **kwargs
obj = models.Tb1(c1='xx', c2='oo') obj.save()
查
models.Tb1.objects.get(id=123) # 获取单条数据,不存在则报错(不建议)
models.Tb1.objects.all() # 获取全部
models.Tb1.objects.filter(name='seven') # 获取指定条件的数据
models.Tb1.objects.exclude(name='seven') # 获取指定条件的数据
删
models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据
改
models.Tb1.objects.filter(name='seven').update(gender='0') # 将指定条件的数据更新,均支持 **kwargs
obj = models.Tb1.objects.get(id=1)
obj.c1 = '111'
obj.save()
二、查询简单操作
获取个数
models.Tb1.objects.filter(name='seven').count()
大于,小于
models.Tb1.objects.filter(id__gt=1) # 获取id大于1的值
models.Tb1.objects.filter(id__gte=1) # 获取id大于等于1的值
models.Tb1.objects.filter(id__lt=10) # 获取id小于10的值
models.Tb1.objects.filter(id__lte=10) # 获取id小于10的值
models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
in
models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
isnull
Entry.objects.filter(pub_date__isnull=True)
contains
models.Tb1.objects.filter(name__contains="ven")
models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
models.Tb1.objects.exclude(name__icontains="ven")
range
models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
其他类似
startswith,istartswith, endswith, iendswith,
order by
models.Tb1.objects.filter(name='seven').order_by('id') # asc
models.Tb1.objects.filter(name='seven').order_by('-id') # desc
group by--annotate
from django.db.models import Count, Min, Max, Sum
models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
limit 、offset
models.Tb1.objects.all()[10:20]
regex正则匹配,iregex 不区分大小写
Entry.objects.get(title__regex=r'^(An?|The) +')
Entry.objects.get(title__iregex=r'^(an?|the) +')
date
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
year
Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__year__gte=2005)
month
Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__month__gte=6)
day
Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3)
week_day
Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)
hour
Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12)
minute
Event.objects.filter(timestamp__minute=29)
Event.objects.filter(time__minute=46)
Event.objects.filter(timestamp__minute__gte=29)
second
Event.objects.filter(timestamp__second=31)
Event.objects.filter(time__second=2)
Event.objects.filter(timestamp__second__gte=31)
三、一对多 使用ForeignKey查询
约束 节省硬盘 但是多表查询会降低速度,大型程序反而不使用外键,而是用单表(约束的时候,通过代码判断)
正向查询
关系模型Enrollment包含关联模型Customer的ForeignKey, 模型Enrollment的实例可以通过关联字段访问Customer实例:
查:
>>> e = Enrollment.objects.get(id=2) #注意:此处不能用e =Enrollment.objects.filter(id=2)
>>> e.customer # 通过上查询到的e对象,关联字段( e.customer )访问到Customer实例
改
e.customer并调用save方法存入数据库
>>> e.customer= some_customer
>>> e.save()
如果ForeignKey 字段有null=True 设置(即它允许NULL值),可以分配None来删除对应的关联性
>>> e.customer= null
>>> e.save()
反向查询
已经得到模型Customer的实例,需要查询该以该实例为外键的相关模型(如FollowUpRecord和Enrollment),可以使用查询集API取出相应的实例。
外键没有指定related_name的相关模型:FollowUpRecord
>>> customer = models.ForeignKey("Customer",on_delete=models.CASCADE)
反查找使用 模型类名小写_set.all() ,方法如下:
>>> c = Customer.objects.get(id=1)
>>> c.followuprecord_set.all()
外键指定related_name的相关模型:FollowUpRecord
customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name='entries')
反查找不能使用 模型类名小写_set.all(),需要使用related_name的值,方法如下:
>>> c = Customer.objects.get(id=1)
>>> c.entries.all()
三、多对多 ManyToMany
class UserGroup(models.Model):
caption = models.CharField(max_length=64)
user_info = models.ManyToManyField('UserInfo')
def __unicode__(self):
return self.caption
user_info_obj = models.UserInfo.objects.get(name='alisa')
user_info_objs = models.UserInfo.objects.all()
group_obj = models.UserGroup.objects.get(caption='CEO')
group_objs = models.UserGroup.objects.all()
# 添加数据
#group_obj.user_info.add(user_info_obj)
group_obj.user_info.add(*user_info_objs)
#例:1,2,3分别代表user_info.的主键id
group_obj.user_info.add(1,2,3)
group_obj.user_info.add([1,2,3])
# 删除数据
#group_obj.user_info.remove(user_info_obj)
#group_obj.user_info.remove(*user_info_objs)
#例:1,2,3分别代表user_info.的主键id
group_obj.user_info.remove(1,2,3)
group_obj.user_info.remove([1,2,3])
# 反向添加数据
#user_info_obj.usergroup_set.add(group_obj)
#user_info_obj.usergroup_set.add(*group_objs)
# 反向删除数据
#user_info_obj.usergroup_set.remove(group_obj)
#user_info_obj.usergroup_set.remove(*group_objs)
# 获取数据
#print group_obj.user_info.all()
#print group_obj.user_info.all().filter(id=1)
#反向 获取数据
#print user_info_obj.usergroup_set.all()
#print user_info_obj.usergroup_set.all().filter(caption='CEO')
#print user_info_obj.usergroup_set.all().filter(caption='DBA')
django model 操作总结的更多相关文章
- Django model操作
一.各种查询统计操作 def all(self) # 获取所有的数据对象 def filter(self, *args, **kwargs) # 条件查询 # 条件可以是:参数,字典,Q def ...
- Django之Model操作
Django之Model操作 本节内容 字段 字段参数 元信息 多表关系及参数 ORM操作 1. 字段 字段列表 AutoField(Field) - int自增列,必须填入参数 primary_ke ...
- Django数据操作F和Q、model多对多操作、Django中间件、信号、读数据库里的数据实现分页
models.tb.objects.all().using('default'),根据using来指定在哪个库里查询,default是settings中配置的数据库的连接名称. 外话:django中引 ...
- Python之路【第二十二篇】:Django之Model操作
Django之Model操作 一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bi ...
- Day19 Django之Form表单验证、CSRF、Cookie、Session和Model操作
一.Form表单验证 用于做用户提交数据的验证1.自定义规则 a.自定义规则(类,字段名==html中的name值)b.数据提交-规则进行匹配代码如下: """day19 ...
- Django(八)下:Model操作和Form操作、序列化操作
二.Form操作 一般会创建forms.py文件,单独存放form模块. Form 专门做数据验证,而且非常强大.有以下两个插件: fields :验证(肯定会用的) widgets:生成HTML(有 ...
- Django(八)上:Model操作和Form操作
↑↑↑点上面的”+”号展开目录 Model和Form以及ModelForm简介 Model操作: 创建数据库表结构 操作数据库表 做一部分的验证 Form操作: 数据验证(强大) ModelForm ...
- Python之路-(Django(csrf,中间件,缓存,信号,Model操作,Form操作))
csrf 中间件 缓存 信号 Model操作 Form操作 csrf: 用 django 有多久,我跟 csrf 这个概念打交道就有久了. 每次初始化一个项目时都能看到 django.middlewa ...
- 03: Django Model数据库操作
目录:Django其他篇 01:Django基础篇 02:Django进阶篇 03:Django数据库操作--->Model 04: Form 验证用户数据 & 生成html 05:Mo ...
随机推荐
- 应用安全 - 无文件式攻击 - 潜伏型攻击 - WMI - 汇总
wbemtest.exe Windows XP Windows 10
- 红帽学习笔记[RHCSA] 第一周
目录 红帽学习笔记[RHCSA] 环境 第一课 关于Shell 命令的基础知识 在终端中敲命令的快捷键 本次课程涉及的命令 第二课 常用的目录结构与用途 本次课程涉及到的命令 第三课 关于Linux的 ...
- 多线程14-Barrier
, b => Console.WriteLine()); ; i <= ; i++) { Console.Write ...
- new 和 malloc 的区别 及使用
Malloc: 定义上:malloc memory allocation 动态内存分配 是c中的一个函数 使用方法: extern void *malloc(unsigned int num_byt ...
- Python3 AES加解密(AES/ECB/PKCS5Padding)
class AesEncry(object): key = "wwwwwwwwwwwwwwww" # aes秘钥 def encrypt(self, data): data = j ...
- win10远程桌面报出现身份验证错误,要求的函数不受支持
win10远程桌面报出现身份验证错误,要求的函数不受支持 编写人:左丘文 2019-6-6 公司换了一台新笔记本电脑,是win10操作系统,刚想远程连接一下服务器,发现以前很正常的功能,发现不行了.网 ...
- 如何配置vsftpd服务器
1,通过yum查看本地是否存在vsftpd rpm -qa|grep vsftpd [root@node2 ~]# rpm -qa |grep vsftpdvsftpd-3.0.2-25.el7.x8 ...
- Python 数据分析:Pandas 缺省值的判断
Python 数据分析:Pandas 缺省值的判断 背景 我们从数据库中取出数据存入 Pandas None 转换成 NaN 或 NaT.但是,我们将 Pandas 数据写入数据库时又需要转换成 No ...
- Animator通过按键切换动画不及时,动画延时切换问题
再unity3D版本为Unity 5.2.1f1 (64-bit),再设置动画切换时有一个Has Exit Time属性,由于勾上了这个的原因
- 利用 TCMalloc 优化 Nginx 的性能
TCMalloc 全称为 Thread-Caching Malloc,是谷歌的开源工具 google-perftools 的成员,它可以 在内存分配效率和速度上高很多,可以很大程度提高服务器在高并发情 ...