본문 바로가기
프로그래밍(Programming)/장고(Django)

[Django] View 안에서 데이터 모델 특정 갯수만 가져오는 방법

by 갈팡이지팡이 2019. 10. 17.

1. 다음과 같이 뷰(View.py) 파일을 작성하세요.

# 특정 앱(appName)의 데이터 모델(ModelName) 로딩
from appName.models import ModelName

def function(request):
    # 인스턴스 생성
    # 데이터 모델의 필드명('id')을 선택
    # 원하는 갯수([:3] = 3개)만큼 쿼리셋 로딩
    instance = ModelName.objects.all().order_by('id')[:3]
    # 'key':value 형태로 데이터 전달
    context = {
        'instance':instance,
    }
    return render(request, '~.html', context)

결과는 instance 라는 이름의 인스턴스에 3개의 쿼리셋이 담겨옵니다.

데이터를 가져오는 순서의 경우 order_by('id')를 기준으로 가져옵니다.