1. 程式人生 > >Django之ORM操作

Django之ORM操作

cursors cap oot 查詢條件 other ddd pos 截取 one

ORM基本增刪改查操作:

技術分享
 1 #
 2 models.Tb1.objects.create(c1=xx, c2=oo)  增加一條數據,可以接受字典類型數據 **kwargs
 3 obj = models.Tb1(c1=xx, c2=oo)
 4 obj.save()
 5 
 6 #
 7 models.Tb1.objects.get(id=123)         # 獲取單條數據,不存在則報錯(不建議)
 8 models.Tb1.objects.all()               # 獲取全部
 9 models.Tb1.objects.filter(name=
seven) # 獲取指定條件的數據 10 models.Tb1.objects.exclude(name=seven) # 獲取指定條件的數據 11 12 # 13 models.Tb1.objects.filter(name=seven).delete() # 刪除指定條件的數據 14 15 # 16 models.Tb1.objects.filter(name=seven).update(gender=0) # 將指定條件的數據更新,均支持 **kwargs 17 obj = models.Tb1.objects.get(id=1) 18 obj.c1 =
111 19 obj.save()# 修改單條數據
增刪改查

ORM進階操作:

技術分享
# 獲取個數
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 models.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 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 不區分大小寫 models.Entry.objects.get(title__regex=r^(An?|The) +) models.Entry.objects.get(title__iregex=r^(an?|the) +) # date import datetime models.Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) models.Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1)) # year models.Entry.objects.filter(pub_date__year=2005) models.Entry.objects.filter(pub_date__year__gte=2005) # month models.Entry.objects.filter(pub_date__month=12) models.Entry.objects.filter(pub_date__month__gte=6) # day models.Entry.objects.filter(pub_date__day=3) models.Entry.objects.filter(pub_date__day__gte=3) # week_day models.Entry.objects.filter(pub_date__week_day=2) models.Entry.objects.filter(pub_date__week_day__gte=2) # hour models.Event.objects.filter(timestamp__hour=23) models.Event.objects.filter(time__hour=5) models.Event.objects.filter(timestamp__hour__gte=12) # minute models.Event.objects.filter(timestamp__minute=29) models.Event.objects.filter(time__minute=46) models.Event.objects.filter(timestamp__minute__gte=29) # second models.Event.objects.filter(timestamp__second=31) models.Event.objects.filter(time__second=2) models.Event.objects.filter(timestamp__second__gte=31)
進階操作

ORM高級操作(Q,F,extra,原生SQL)

技術分享
#extra
#extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
models.Entry.objects.extra(select={new_id: "select col from sometable where othercol > %s"}, select_params=(1,))
#select *,(select col from sometable where otherco >1) as new_id from Entry
models.Entry.objects.extra(where=[headline=%s], params=[Lennon])
#select * from Entry where headline=‘Lennon‘
models.Entry.objects.extra(where=["foo=‘a‘ OR bar = ‘a‘", "baz = ‘a‘"])
#select * from Entry where foo=‘a‘ or bar = ‘a‘ and baz=‘a‘
models.Entry.objects.extra(select={new_id: "select id from tb where id > %s"},
                           select_params=(1,), order_by=[-nid])
#select *,(select id from tb where id > 1) from Entry order nid desc

#F
from django.db.models import F
models.Tb1.objects.update(num=F(num)+1)
#先引用(F(‘num‘)+1  用來將原始值取出並+1),再賦值(num=F(‘num‘)+1)相當於,num+1之後更新


#Q
from django.db.models import Q
#方式一:
Q(nid__gt=10)
#where nid > 10
Q(nid=8) | Q(nid__gt=10)
#where nid =8 or nid >10
Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=root)
# 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))
# q1 : where id =1 or id=10 or id=9 
q2 = Q()
q2.connector = OR
q2.children.append((c1, 1))
q2.children.append((c1, 10))
q2.children.append((c1, 9))
#q2 :where c1=1 or c1=10 or c1=9
con.add(q1, AND)
con.add(q2, AND)
#con: where (id =1 or id=10 or id=9 ) and (c1=1 or c1=10 or c1=9)
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()  
#拿到默認數據庫default連接的遊標
cursors = connections[db1].cursor()
#拿到指定數據庫db1的遊標
cursor.execute("""SELECT * from auth_user where id = %s""", [1])
row = cursor.fetchone()
ORM高階操作

ORM其他操作(ORM對象方法拆解)

技術分享
##################################################################
# PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
##################################################################

def all(self)
    # 獲取所有的數據對象

def filter(self, *args, **kwargs)
    # 條件查詢
    # 條件可以是:參數,字典,Q

def exclude(self, *args, **kwargs)
    # 條件查詢
    # 條件可以是:參數,字典,Q

def select_related(self, *fields)
     性能相關:表之間進行join連表操作,一次性獲取關聯的數據。
     model.tb.objects.all().select_related()
     model.tb.objects.all().select_related(外鍵字段)
     model.tb.objects.all().select_related(外鍵字段__外鍵字段)

def prefetch_related(self, *lookups)
    性能相關:多表連表操作時速度會慢,使用其執行多次SQL查詢在Python代碼中實現連表操作。
            # 獲取所有用戶表
            # 獲取用戶類型表where id in (用戶表中的查到的所有用戶ID)
            models.UserInfo.objects.prefetch_related(外鍵字段)



            from django.db.models import Count, Case, When, IntegerField
            Article.objects.annotate(
                numviews=Count(Case(
                    When(readership__what_time__lt=treshold, then=1),
                    output_field=CharField(),
                ))
            )

            students = Student.objects.all().annotate(num_excused_absences=models.Sum(
                models.Case(
                    models.When(absence__type=Excused, then=1),
                default=0,
                output_field=models.IntegerField()
            )))

def annotate(self, *args, **kwargs)
    # 用於實現聚合group by查詢

    from django.db.models import Count, Avg, Max, Min, Sum

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id)).filter(uid__gt=1)
    # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    v = models.UserInfo.objects.values(u_id).annotate(uid=Count(u_id,distinct=True)).filter(uid__gt=1)
    # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

def distinct(self, *field_names)
    # 用於distinct去重
    models.UserInfo.objects.values(nid).distinct()
    # select distinct nid from userinfo

    註:只有在PostgreSQL中才能使用distinct進行去重

def order_by(self, *field_names)
    # 用於排序
    models.UserInfo.objects.all().order_by(-id,age)

def 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])

 def reverse(self):
    # 倒序
    models.UserInfo.objects.all().order_by(-nid).reverse()
    # 註:如果存在order_by,reverse則是倒序,如果多個排序則一一倒序


 def defer(self, *fields):
    models.UserInfo.objects.defer(username,id)
    或
    models.UserInfo.objects.filter(...).defer(username,id)
    #映射中排除某列數據

 def only(self, *fields):
    #僅取某個表中的數據
     models.UserInfo.objects.only(username,id)
     或
     models.UserInfo.objects.filter(...).only(username,id)

 def using(self, alias):
     指定使用的數據庫,參數為別名(setting中的設置)


##################################################
# PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
##################################################

def raw(self, raw_query, params=None, translations=None, using=None):
    # 執行原生SQL
    models.UserInfo.objects.raw(select * from userinfo)

    # 如果SQL是其他表時,必須將名字設置為當前UserInfo對象的主鍵列名
    models.UserInfo.objects.raw(select id as nid from 其他表)

    # 為原生SQL設置參數
    models.UserInfo.objects.raw(select id as nid from userinfo where nid>%s, params=[12,])

    # 將獲取的到列名轉換為指定列名
    name_map = {first: first_name, last: last_name, bd: birth_date, pk: id}
    Person.objects.raw(SELECT * FROM some_other_table, translations=name_map)

    # 指定數據庫
    models.UserInfo.objects.raw(select * from userinfo, using="default")

    ################### 原生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() # fetchall()/fetchmany(..)


def values(self, *fields):
    # 獲取每行數據為字典格式

def values_list(self, *fields, **kwargs):
    # 獲取每行數據為元祖

def dates(self, field_name, kind, order=ASC):
    # 根據時間進行某一部分進行去重查找並截取指定內容
    # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日)
    # order只能是:"ASC"  "DESC"
    # 並獲取轉換後的時間
        - year : 年-01-01
        - month: 年-月-01
        - day  : 年-月-日

    models.DatePlus.objects.dates(ctime,day,DESC)

def datetimes(self, field_name, kind, order=ASC, tzinfo=None):
    # 根據時間進行某一部分進行去重查找並截取指定內容,將時間轉換為指定時區時間
    # kind只能是 "year", "month", "day", "hour", "minute", "second"
    # order只能是:"ASC"  "DESC"
    # tzinfo時區對象
    models.DDD.objects.datetimes(ctime,hour,tzinfo=pytz.UTC)
    models.DDD.objects.datetimes(ctime,hour,tzinfo=pytz.timezone(Asia/Shanghai))

    """
    pip3 install pytz
    import pytz
    pytz.all_timezones
    pytz.timezone(‘Asia/Shanghai’)
    """

def none(self):
    # 空QuerySet對象


####################################
# METHODS THAT DO DATABASE QUERIES #
####################################

def aggregate(self, *args, **kwargs):
   # 聚合函數,獲取字典類型聚合結果
   from django.db.models import Count, Avg, Max, Min, Sum
   result = models.UserInfo.objects.aggregate(k=Count(u_id, distinct=True), n=Count(nid))
   ===> {k: 3, n: 4}

def count(self):
   # 獲取個數

def get(self, *args, **kwargs):
   # 獲取單個對象

def create(self, **kwargs):
   # 創建對象

def bulk_create(self, objs, batch_size=None):
    # 批量插入
    # batch_size表示一次插入的個數
    objs = [
        models.DDD(name=r11),
        models.DDD(name=r22)
    ]
    models.DDD.objects.bulk_create(objs, 10)

def get_or_create(self, defaults=None, **kwargs):
    # 如果存在,則獲取,否則,創建
    # defaults 指定創建時,其他字段的值
    obj, created = models.UserInfo.objects.get_or_create(username=root1, defaults={email: 1111111,u_id: 2, t_id: 2})

def update_or_create(self, defaults=None, **kwargs):
    # 如果存在,則更新,否則,創建
    # defaults 指定創建時或更新時的其他字段
    obj, created = models.UserInfo.objects.update_or_create(username=root1, defaults={email: 1111111,u_id: 2, t_id: 1})

def first(self):
   # 獲取第一個

def last(self):
   # 獲取最後一個

def in_bulk(self, id_list=None):
   # 根據主鍵ID進行查找
   id_list = [11,21,31]
   models.DDD.objects.in_bulk(id_list)

def delete(self):
   # 刪除

def update(self, **kwargs):
    # 更新

def exists(self):
   # 是否有結果

其他操作
其他操作

Django之ORM操作