장고 쿼리 뿌시기

정은경·2021년 9월 7일
0

Lazy Evaluation

  • Django ORM doesn't make the SQL calls until the data is actually needed

Query Expressions

Database Functions

db_index

db_index=True

언제 index를 걸어야할까?

  • 처음부터 index를 이용할 필요는 없다. 필요가 보이면 건다.
  • index를 거는 것을 고려해야하는 경우들:
    * 전체 쿼리에 10-25%를 차지하는 경우
    • real data가 있는 경우, 인덱싱의 결과를 분석할 수 있음
    • index가 결과에 도움을 주는 지 테스트를 해볼 수 있음

Transactions

  • The default behavior of the ORM is to autocommit every query when it is called.
  • The disadvantage if that if a view (or some other operation) requires two or more database modifications to occur, if one modification succeeds and the other fails, the database is at risk of corruption.
  • The way to resovle the risk of database corruption is through the use of database transactions.

database transaction

  • where two or more database updates are contained in a single unit of work

atomic_requests

# settings/base.py

DATABASES = {
	'default': {
    	# ...
        'ATOMIC_REQUESTS': True,
    },
}

wrapping each HTTP request in a transaction

# flavors/views.py

from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone

from .models import Flavor


@transaction.non_atomic_requests
def posting_flavor_status(request, pk, status):
	flavor = get_object_or_404(Flavor, pk=pk)
    
    # this will execute in autocommit mode (Django's default).
    flavor.latest_status_change_attempt = timezone.now()
    flavor.save()
    
    with transaction.atomic():
    	# this code executes inside a transaction
        flavor.status = status
        flavor.latest_status_change_success = timezone.now()
        flavor.save()
        return HttpResponse('Hooray')
    
    # if the transaction fails, return the appropriate status
    return HttpResponse('Sadness', status_code=400)

Reference

profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글