django orm 操作表

1、基本操作

models.Tb1.objects.create(c1='xx', c2='oo')  增加一条数据,可以接受字典类型数据 **kwargs
insert into Tb1 (c1,c2) values ('xx','00')
obj = models.Tb1(c1='xx', c2='oo')
obj.save()
insert into Tb1 (c1,c2) values ('xx','00')# get_or_create()  如果纯在则获取,否者创建
obj, created = models.UserInfo.objects.get_or_create(name='summer1',defaults={'age':123,'pwd':'ab456'})
# 先根据条件去查,如果存在name='summer1',则后面的default无效不执行。
print(obj,created) # created 为True或False# update_or_create() 如果存在,则更新,否则,创建
obj, created = models.UserInfo.objects.update_or_create(name='summer1',defaults={'age':123,'pwd':'ab456'})print(obj,created)

models.Tb1.objects.get(id=123)         # 获取单条数据,不存在则报错(不建议)
select * from Tb1 where id=123 limit 1
models.Tb1.objects.all()               # 获取全部
select * from Tb1
models.Tb1.objects.filter(name='seven') # 获取指定条件的数据
select * from Tb1 where name='seven'# exists()
# 检查查询结果是否存在,返回True或False
result = models.UserInfo.objects.filter(id=1111).exists()
print(result)

models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据
delete from Tb1 where name='seven'

models.Tb1.objects.filter(name='seven').update(gender='0')  # 将指定条件的数据更新,均支持 **kwargs
update Tb1 set gender='0' where name='seven'
obj = models.Tb1.objects.get(id=1)
obj.c1 = '111'
obj.save()                                                 # 修改单条数据
update Tb1 set c1 = '111' where id=1

 

2、进阶操作(了不起的双下划线)

利用双下划线将字段和对应的操作连接起来

  • 获取个数

      models.Tb1.objects.filter(name='seven').count()select count(*) from Tb1 where name='seven'

  • 大于,小于

      models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值select * from Tb1 where id>1models.Tb1.objects.filter(id__gte=1)              # 获取id大于等于1的值select * from Tb1 where id>=1models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值select * from Tb1 where id<10models.Tb1.objects.filter(id__lte=10)             # 获取id小于等于10的值select * from Tb1 where id<=10models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值select * from Tb1 where id<10 and id>1

  • in

     models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据select * from Tb1 where id in (11, 22, 33)models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not inselect * from Tb1 where id not in (11, 22, 33)

  • isnull

     Entry.objects.filter(pub_date__isnull=True)select * from Tb1 where pub_date is null

  • contains

    models.Tb1.objects.filter(name__contains="ven")select * from Tb1 where name like binary '%ven%'models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感select * from Tb1 where name like  '%ven%'models.Tb1.objects.exclude(name__icontains="ven")select * from Tb1 where name not like '%ven%'

  • range

     models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen andselect * from Tb1 where id bettwen 1 and 2

  • 其他类似

    startswith,istartswith, endswith, iendswith,startswith select * from Tb1 where name like  'ven%'endswith  select * from Tb1 where name like  '%ven'

  • order by

     models.Tb1.objects.filter(name='seven').order_by('id')    # ascselect * from Tb1 where name='seven' order by id ascmodels.Tb1.objects.filter(name='seven').order_by('-id')   # descselect * from Tb1 where name='seven' order by id desc

  • group by

      from django.db.models import Count, Min, Max, Summodels.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]select * from Tb1 limit 10,20

  • regex正则匹配,iregex 不区分大小写

      Entry.objects.get(title__regex=r'^(An?|The) +')select * from Entry where title regexp binary "^(An?|The) +"Entry.objects.get(title__iregex=r'^(an?|the) +')select * from Entry where title regexp "^(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)

3、其他操作

  • extra

     extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))Entry.objects.extra(where=['headline=%s'], params=['Lennon'])Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

  • F

      from django.db.models import Fmodels.Tb1.objects.update(num=F('num')+1)update Tb1 set num=num+1

  • Q

      from django.db.models import Q方式一:Q(nid__gt=10)Q(nid=8) | Q(nid__gt=10)select * from table where nid=8 or nid>10Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')select * from Tb1 where (nid=8 or nid>10) and caption='root'方式二:con = Q()q1 = Q()q1.connector = 'OR'q1.children.append(('id', 1))q1.children.append(('id', 10))q1.children.append(('id', 9))q2 = Q()q2.connector = 'OR'q2.children.append(('c1', 1))q2.children.append(('c1', 10))q2.children.append(('c1', 9))con.add(q1, 'AND')con.add(q2, 'AND')models.Tb1.objects.filter(con)select * from Tb1 where ( id=1 or id=10 or id=9 ) and ( c1=1 or c1=10 or c1=9 )

  • 执行原生SQL

      from django.db import connection, connectionscursor = connection.cursor()  # cursor = connections['default'].cursor()cursor.execute("""SELECT * from auth_user where id = %s""", [1])row = cursor.fetchone()

4、连表操作(了不起的双下划线)

利用双下划线和 _set 将表之间的操作连接起来

  • 表结构实例
class UserProfile(models.Model):user_info = models.OneToOneField('UserInfo')username = models.CharField(max_length=64)password = models.CharField(max_length=64)def __str__(self):return self.usernameclass UserInfo(models.Model):user_type_choice = ((0, '普通用户'),(1, '高级用户'),)user_type = models.IntegerField(choices=user_type_choice)name = models.CharField(max_length=32)email = models.CharField(max_length=32)address = models.CharField(max_length=128)def __str__(self):return self.nameclass UserGroup(models.Model):caption = models.CharField(max_length=64)user_info = models.ManyToManyField('UserInfo')def __str__(self):return self.captionclass Host(models.Model):hostname = models.CharField(max_length=64)ip = models.GenericIPAddressField()user_group = models.ForeignKey('UserGroup')def __str__(self):return self.hostname

  • 一对一操作

      user_info_obj = models.UserInfo.objects.filter(id=1).first()print (user_info_obj.user_type)select user_type drom UserInfo where id=1 limit 1print (user_info_obj.get_user_type_display())print (user_info_obj.userprofile.password)select userprofile.password from userprofile,UserInfo where UserInfo.id=1 and UserInfo.id=userprofile.user_infouser_info_obj = models.UserInfo.objects.filter(id=1).values('email', 'userprofile__username').first()select email, userprofile.username from UserInfo,userprofile where UserInfo.id=1 and UserInfo.id=userprofile.user_infoprint (user_info_obj.keys())print (user_info_obj.values())

  • 一对多

      类似一对一1、搜索条件使用 __ 连接2、获取值时使用 .    连接
    
  • 多对多操作

      user_info_obj = models.UserInfo.objects.get(name=u'武沛齐')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)# 删除数据
      group_obj.user_info.remove(user_info_obj)group_obj.user_info.remove(*user_info_objs)# 添加数据
      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')

转载于:https://www.cnblogs.com/jiangwenhui/p/10154031.html

django orm 操作表相关推荐

  1. Django ORM操作

    Django ORM操作 一般操作 看专业的官网文档,做专业的程序员! 必知必会13条 <1> all(): 查询所有结果<2> get(**kwargs): 返回与所给筛选条 ...

  2. django mysql orm教程_带你了解Django ORM操作(基础篇)

    前言 在日常开发中,需要大量对数据库进行增删改查操作. 如果头铁的话,使用原生SQL是最好的,毕竟性能又高,又灵活. 但是通常情况下,我们不是太需要那么苛刻的性能,也没有那么多刁钻的需求用原生SQL ...

  3. Django ORM那些相关操作

    一般操作 https://docs.djangoproject.com/en/1.11/ref/models/querysets/         官网文档 常用的操作 <1> all() ...

  4. django orm级联_Django数据表关联关系映射(一对一、一对多、多对多)

    我们知道涉及到数据表之间的对应关系就会想到一对一.一对多.多对多,在学习 MySQL 数据库时表关系设计是需要重点掌握的知识.Django 中定义了三种关系类型的字段用来描述数据库表的关联关系:一对多 ...

  5. django ORM相关的那些操作汇总

    必知必会13条 <1> all(): 查询所有结果<2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象<3> get(**kwargs): ...

  6. django ORM中的RelatedManager(关联管理器)

    关联管理器应用在 一对多的表 或者 多对多的表 多对多表中的用法: 在多对多的表中 正向查询 #基于对象的查询 #正查 # author_obj = Author.objects.get(id=1) ...

  7. Django ORM

    Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/cou ...

  8. Django ORM 知识点总结

    Query是如何工作的 Django QuerySet是懒执行的,只有访问到对应数据的时候,才会去访问数据库.另外如果你再次读取查询到的数据,将不会触发数据库的访问,而是直接从缓存获取. 比如 # 这 ...

  9. Django - ORM操作

    Django - ORM操作 一. 必知必会13条 单表查询之神奇的双下划线 二. ForeignKey操作 正向查找 反向操作 三. ManyToManyField 四. 聚合查询和分组查询 聚合 ...

  10. Django ORM 数据库操作

    比较有用 转自 http://blog.csdn.net/fgf00/article/details/53678205 一.DjangoORM 创建基本类型及生成数据库表结构 1.简介 2.创建数据库 ...

最新文章

  1. Busybox 设置登录用户名、密码
  2. Find First and Last Position of Element in Sorted Array
  3. 华为手机丢失定位网站_手机端网站优化要从网站的设计和定位开始入手
  4. 初学 Delphi 嵌入汇编[18] - SHL 与 SHR
  5. 用python写一个简单的web服务器
  6. Do you know? -- season 1
  7. Linux 与 Windows 计算文件夹大小
  8. 马尔科夫蒙特卡洛算法(MCMC)
  9. 斐讯K3C官改V1.7D降级至官改V1.6
  10. 2021新版CISSP考试大纲解析
  11. lae界面开发工具入门之介绍八--消息转发器组件篇
  12. 2.6.机载测深激光扫描系统—(Topographic Laser Ranging and Scanning-Principle 读书笔记)
  13. 从第三方应用跳回uniapp开发的app
  14. 微信订阅号小技巧及相关知识普及
  15. 视频融合技术平台解决方案
  16. InnoDB关键特性之插入缓冲
  17. 什么是欧拉角/姿态角?
  18. ltsc系统升级为服务器,微软宣布Win11将像Win10一样每月提供更新 且有长期服务版本LTSC...
  19. 浅谈架构、操作系统、芯片的理解
  20. PCB线路板阻焊油墨脱落的原因

热门文章

  1. KNN(六)--LSH算法
  2. layui列表筛选列_layui框架的table字段筛选功能介绍
  3. kafka--Struct Streaming--mysql案例
  4. 如何优雅的show出你的代码?
  5. HBase实战 | 从MySQL到HBase:数据存储方案转型的演进
  6. ThinkSNS Plus PHP开发概述
  7. or1200处理器的异常处理类指令介绍
  8. mysql删除重复记录只保留一条
  9. autorun.inf sxs.exe病毒手动解决方法
  10. yum命令报错 yum update File /usr/bin/yum, line 30 except KeyboardInterrupt, e: --CentOS7.5