Django 의 model 조회 조작 과 조회 성능 최적화

1.ORM 조 회 를 할 때 SQL 의 실행 상황 을 보 는 방법
(1)밑바닥 django.db.connection
django 셸 에서 사용  python manage.py shell

>>> from django.db import connection
>>> Books.objects.all()
>>> connection.queries  ##         
[{'sql': 'SELECT "testsql_books"."id", "testsql_books"."name", "testsql_books"."author_id" FROM "testsql_books" LIMI
T 21', 'time': '0.002'}]
(2)django-extensions 플러그 인 

pip install django-extensions

 INSTALLED_APPS = (
    ...
    'django_extensions',
    ...
    )
django 셸 에서 사용  python manage.py shell_plus  --print-sql(확장 기능 강화)
이렇게 검색 할 때마다 sql 출력 이 있 습 니 다.

>>> from testsql.models import Books
>>> Books.objects.all()
  SELECT "testsql_books"."id", "testsql_books"."name", "testsql_books"."author_id" FROM "testsql_books" LIMIT 21

Execution time: 0.002000s [Database: default]

<QuerySet [<Books: Books object>, <Books: Books object>, <Books: Books object>]>
2 ORM 조회 조작 및 최적화
기본 조작

 

models.Tb1.objects.create(c1='xx', c2='oo')       ,           **kwargs

obj = models.Tb1(c1='xx', c2='oo')
obj.save()

  

models.Tb1.objects.get(id=123)     #       ,      (   )
models.Tb1.objects.all()        #     
models.Tb1.objects.filter(name='seven') #          
models.Tb1.objects.exclude(name='seven') #          

  

models.Tb1.objects.filter(name='seven').delete() #          

  
models.Tb1.objects.filter(name='seven').update(gender='0') #           ,    **kwargs
obj = models.Tb1.objects.get(id=1)
obj.c1 = '111'
obj.save()                         #       

조회 단순 조작

    

  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
  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--annotate

  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       

  Entry.objects.get(title__regex=r'^(An?|The) +')
  Entry.objects.get(title__iregex=r'^(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)

조회 복잡 조작
FK foreign key 사용 이유:
  • 구속
  • 하 드 디스크 절약
  • 그러나 다 중 표 조 회 는 속 도 를 낮 추고 대형 프로그램 은 오히려 외 키 를 사용 하지 않 고 단일 표(제약 할 때 코드 로 판단)를 사용한다.
    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)
    Q
    
         :
      Q(nid__gt=10)
      Q(nid=8) | Q(nid__gt=10)
      Q(Q(nid=8) | Q(nid__gt=10)) & Q(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)
    
    exclude(self, *args, **kwargs)
    
      #     
      #      :  ,  ,Q
    select_related(self, *fields)
    
           :     join    ,          。
       model.tb.objects.all().select_related()
       model.tb.objects.all().select_related('    ')
       model.tb.objects.all().select_related('    __    ')
    
    prefetch_related(self, *lookups)
    
          :           ,       SQL          ,         
          #            
          #            where id in (            ID)
          models.UserInfo.objects.prefetch_related('    ')
    
    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
    
    
    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'])
    
    
    reverse(self):
    
    #   
    models.UserInfo.objects.all().order_by('-nid').reverse()
    #  :    order_by,reverse    ,           
    다음 두 개 는 대상 을 찾 을 수 있 으 며,찾 은 대상 은 다른 필드 를 가 져 올 수 있 습 니 다.(이 필드 를 다시 찾 아 성능 을 떨 어 뜨 립 니 다.
    defer(self, *fields):
    
     models.UserInfo.objects.defer('username','id')
     
    models.UserInfo.objects.filter(...).defer('username','id')
    #          
    
    only(self, *fields):
    
    #          
    models.UserInfo.objects.only('username','id')
     
    models.UserInfo.objects.filter(...).only('username','id')
    
    네 이 티 브 SQL 실행
    
    1.connection
    from django.db import connection, connections
    cursor = connection.cursor() 
    # cursor = connections['default'].cursor()
    django settings  db   ' default',     
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone()
    
    2 .extra
    Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])
    
    3 . raw     
    name_map = {'a':'A','b':'B'}
    models.UserInfo.objects.raw('select * from xxxx',translations=name_map)
    
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기