django orm 操作表

1、基本操作

models.Tb1.objects.create(c1='xx', c2='oo')  增加一条数据,可以接受字典类型数据 **kwargs
insert into Tb1 (c1,c2) values ('xx','')
obj = models.Tb1(c1='xx', c2='oo')
obj.save()
insert into Tb1 (c1,c2) values ('xx','') # 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='')  # 将指定条件的数据更新,均支持 **kwargs
update Tb1 set gender='' where name='seven'
obj = models.Tb1.objects.get(id=1)
obj.c1 = ''
obj.save() # 修改单条数据
update Tb1 set c1 = '' 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>1
    models.Tb1.objects.filter(id__gte=1) # 获取id大于等于1的值
    select * from Tb1 where id>=1
    models.Tb1.objects.filter(id__lt=10) # 获取id小于10的值
    select * from Tb1 where id<10
    models.Tb1.objects.filter(id__lte=10) # 获取id小于等于10的值
    select * from Tb1 where id<=10
    models.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 in
    select * 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 and
    select * 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')    # asc
    select * from Tb1 where name='seven' order by id asc
    models.Tb1.objects.filter(name='seven').order_by('-id') # desc
    select * from Tb1 where name='seven' order by id desc
  • group by

      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]
    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 F
    models.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>10
    Q(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, connections
    cursor = 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.username class 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.name class UserGroup(models.Model): caption = models.CharField(max_length=64) user_info = models.ManyToManyField('UserInfo') def __str__(self):
return self.caption class 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 1
    print (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_info user_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_info
    print (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')

django orm 操作表的更多相关文章

  1. Python - Django - ORM 操作表

    ORM 的对应关系: 类        --->    数据库表对象     --->    数据库行属性     --->    字段 操作数据库表     --->     ...

  2. Django ORM创建数据库

    Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...

  3. django -orm操作总结

    前言 Django框架功能齐全自带数据库操作功能,本文主要介绍Django的ORM框架 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MyS ...

  4. Django 2.0 学习(14):Django ORM 数据库操作(上)

    Django ORM 数据库操作(上) ORM介绍 映射关系: 数据库表名 ---------->类名:数据库字段 ---------->类属性:数据库表一行数据 ----------&g ...

  5. 【python】-- Django ORM(进阶)

    Django ORM(进阶) 上一篇博文简述了Django ORM的单表操作,在本篇博文中主要简述Django ORM的连表操作. 一.一对多:models.ForeignKey() 应用场景:当一张 ...

  6. 数据库开发-Django ORM的多对多查询

    数据库开发-Django ORM的多对多查询 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.联合主键问题 CREATE TABLE `employees` ( `emp_no` ...

  7. django orm总结[转载]

    django orm总结[转载] 转载地址: http://www.cnblogs.com/linjiqin/archive/2014/07/01/3817954.html 目录1.1.1 生成查询1 ...

  8. Django ORM - 001 - 外键表查询主表信息

    开始用Django做web开发,我想大家都会遇到同样的问题,那就是如何高效快速的查询需要的数据,MVC都很简单,但是ORM折腾起来就有些费时间,我准备好好研究下Django ORM,所以会有一个系列的 ...

  9. Django ORM 中的批量操作

    Django ORM 中的批量操作 在Hibenate中,通过批量提交SQL操作,部分地实现了数据库的批量操作.但在Django的ORM中的批量操作却要完美得多,真是一个惊喜. 数据模型定义 首先,定 ...

随机推荐

  1. BZOJ3747:[POI2015]Kinoman(线段树)

    Description 共有m部电影,编号为1~m,第i部电影的好看值为w[i]. 在n天之中(从1~n编号)每天会放映一部电影,第i天放映的是第f[i]部. 你可以选择l,r(1<=l< ...

  2. Dictionary<string, object>

    Dictionary<string, object> dcic = JsonHelper.DataRowFromJSON(resultdepth); foreach (var depthk ...

  3. PHP运行模式简单总结

    众所周知,PHP有多种运行模式,那么这些模式各自有什么特点,它们之间又有什么区别呢,本文将作一个简单的总结: CGI 模式 所谓 CGI (Common Gateway Interface) 是指通用 ...

  4. weblogic之CVE-2018-3191漏洞分析

    weblogic之CVE-2018-3191漏洞分析 理解这个漏洞首先需要看这篇文章:https://www.cnblogs.com/afanti/p/10193169.html 引用廖新喜说的,说白 ...

  5. Hive学习之路 (二)Hive安装

    Hive的下载 下载地址http://mirrors.hust.edu.cn/apache/ 选择合适的Hive版本进行下载,进到stable-2文件夹可以看到稳定的2.x的版本是2.3.3 Hive ...

  6. CS231N assignment1

    # Visualize some examples from the dataset. # We show a few examples of training images from each cl ...

  7. 【题解】洛谷P2577 [ZJOI2005] 午餐(DP+贪心)

    次元传送门:洛谷P2577 思路 首先贪心是必须的 我们能感性地理解出吃饭慢的必须先吃饭(结合一下生活) 因此我们可以先按吃饭时间从大到小排序 然后就能自然地想到用f[i][j][k]表示前i个人在第 ...

  8. js随笔记录

     1.当我们尝试优化一段程序的时候,必须要同时了解语言本身和运行环境就比如说,可能教科书上写移位操作比乘法运算要快,但是这是因为CPU指令的问题,所以对于C语言成立,对于跑在VM上的语言来说则不一定了 ...

  9. mysql8.0.15安装

    1. 官网下载mysql,此处下载的是.zip文件 2. 解压下载的文件夹,并且配置环境变量:Path : E:\mysql-8.0.15-winx64\bin 3. 配置my.ini文件 4. 以管 ...

  10. 在jupyter中安装R的kernal

    网上有安装完anaconda后可以直接使用conda 命令安装R的kernal,本人电脑上已经安装了anaconda和R,因此使用手动安装的方式安装. 安装环境: windows 8.1 企业版 An ...