django orm 操作表
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‘) # 查 # # 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‘ # 刪 # # 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, # 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 操作表