API 경로에 동적값을 받을 때가 있다.
from django.urls import include, path
from rest_framework import routers
from . import views #views.py
urlpatterns = [
path('test/<index>', views.getText),
]
이렇게 경로 뒤에 <>를 붙혀 값을 전달한다.
view 쪽에서 이 값을 받게 되어 있어한다.
from rest_framework.response import Response
from rest_framework import viewsets
from .serializers import TestSerializer
from .models import Test
from rest_framework.decorators import api_view
@api_view(['GET'])
def getText(request, index):
print(index)
# queryset = Test.objects.all() # 전체 조회
queryset = Test.objects.filter(id = index) # 해당 id만 조회
print(queryset)
serializer = TestSerializer(queryset, many=True)
return Response(serializer.data)
index라는 값을 인자로 받는 getText()이다.
.all()이 아닌 .filter()를 사용해서 id가 index인 데이터만 조회한다.
쿼리문 자체 실행하기
조회할 데이터의 조건이 복잡하면 쿼리로 날려서 조회해야 할 때가 있을 것이다.
방법 1. connection을 사용해서 쿼리를 입력한다.
이 때는 따로 model을 정의하지 않아도 된다.
@api_view(['GET'])
def getText(request, index):
print(index)
conn = connection.cursor()
conn.execute("SELECT * FROM my_django_api_test WHERE id = %s", [index])
result = conn.fetchone()
print(result)
return Response(result)
방법2. model에 직접 쿼리를 적용한다.
@api_view(['GET'])
def getTest(request, index):
print(index)
result = Test.objects.raw("SELECT * FROM my_django_api_test WHERE id = %s", [index])
print(result)
serializer = TestSerializer(result, many=True)
return Response(serializer.data)
'dev > django' 카테고리의 다른 글
Django insert (0) | 2023.04.09 |
---|---|
Django Rest Framework (0) | 2023.04.09 |
Django 설치, 가상환경 (0) | 2023.04.09 |
Django MariaDB 연동 (0) | 2023.04.08 |
맥OS Django 실행 (0) | 2023.03.26 |