1. 程式人生 > >Django-ORM進階操作01

Django-ORM進階操作01

  • 1.增刪改查
  • 2.一般操作:
models.UserInfo.objects.filter(id__gt=1)
models.UserInfo.objects.filter(id__lt=1)
models.UserInfo.objects.filter(id__lte=1)
models.UserInfo.objects.filter(id__gte=1)
models.UserInfo.objects.filter(id__in=[1,2,3])
models.UserInfo.objects.filter(id__range=[1,2])
models.UserInfo.objects.filter
(name__startswith='au') models.UserInfo.objects.filter(name__contains='au') # 包含 models.UserInfo.objects.exclude(id=1) # 排除,除去括號內的條件之外的內容。
  • 3.排序:
user_object_list = models.UserInfo.objects.all().order_by('id') # asc

user_object_list = models.UserInfo.objects.all().order_by('-id') # desc

user_object_list = models.UserInfo.objects.all().order_by('-id'
,'name') # 如果遇到id相等 按name從小到大排序
  • 4.分組:
    from django.db.models import Count

    v = models.UserInfo.objects.values('ut_id').annotate(aa = Count('id'))
    print(v.query)
    # SELECT "app01_userinfo"."ut_id", COUNT("app01_userinfo"."id") AS "aa" FROM "app01_userinfo" GROUP BY "app01_userinfo"
."ut_id" for item in v: print(item) v = models.UserInfo.objects.values('ut_id').annotate(aa = Count('id')).filter(aa__gte=2) v = models.UserInfo.objects.filter(id__gt=2).values('ut_id').annotate(aa = Count('id')).filter(aa__gte=2) # filter()放在前面相等於where 放在annotate後相當於having
  • 5.F, Q, extra
    # F 更新時獲取原變數數值

    from django.db.models import F,Q

    models.UserInfo.objects.all().update(age=F('age')+1)

    user_List = models.UserInfo.objects.filter(id__lt=20).values('age')
    for row in user_List:
        print(row['age'])
    from django.db.models import Q



    models.UserInfo.objects.filter(id=1,name='spring')
    condition = {
        'id':1,
        'name':'spring',
    }
    v = models.UserInfo.objects.filter(**condition)




    from django.db.models import Q
  • Q 用於構造複雜的查詢條件
    # Q 用於構造複雜的查詢條件

    # Q 的第一種寫法
    models.UserInfo.objects.filter(Q(id=1))
    models.UserInfo.objects.filter(Q(id=1) | Q(id=2))
    models.UserInfo.objects.filter(Q(id=3) & Q(id=4))

    # 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(('ut_id',1))
    q2.children.append(('ut_id',2))

    con = Q()
    con.add(q1,'AND')
    con.add(q2,'AND')

  • extra
    # extra


    v = models.UserInfo.objects.all().extra(select={'n':'select count(1) from app01_userinfo'})

    v = models.UserInfo.objects.all().extra(select={'n':'select count(1) from app01_userinfo WHERE id > 100'})

    v = models.UserInfo.objects.all().extra(select={'n':'select count(1) from app01_userinfo WHERE id > %s'},select_params=[100,])
    v = models.UserInfo.objects.all().extra(select={'n':'select count(1) from app01_userinfo WHERE id = %s or id = %s' },select_params=[100,201])

    v = models.UserInfo.objects.all().extra(select={
    'n':'select count(1) from app01_userinfo WHERE id = %s or id = %s' ,
    'm':'select count(1) from app01_userinfo WHERE id = %s or id = %s' ,
    },
    select_params=[3,4,100,201])


    v = models.UserInfo.objects.extra(
        where=['id=%s or id=2','name=%s'],
        params=[1,'summer'],
        order_by=['-id']
    )


    v = models.UserInfo.objects.extra(
        tables=['app01_usertype'],  # 笛卡爾基
        where=['app01_usertype.id = app01_userinfo.ut_id']
    )


  • 原生SQL語句
setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'db2': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db2',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}



    # 原生 SQL語句

    from django.db import connection,connections
    cursor = connection.cursor() # 用預設default的資料庫
    cursor = connections['db2'].cursor() # 使用db2 資料庫

    cursor.execute('select * from app01_userinfo WHERE id = %s',[1,])

    row = cursor.fetchone()