欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django orm 操作表

程序员文章站 2022-09-03 09:26:04
django orm 操作表 1、基本操作 增 查 删 改 2、进阶操作(了不起的双下划线) 利用双下划线将字段和对应的操作连接起来 获取个数 models.Tb1.objects.filter(name='seven').count() select count(*) from Tb1 where ......

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>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')