parameter(파라미터) 사용법

Nicholas·2022년 5월 29일
0

Django

목록 보기
9/14

RESTful API에서 frontend 와 backend 통신에서 자주 사용되는 parameter(파라미터)사용법

1. path parameter

  • 경로를 넣어 통신하는 방법

Django에서 path parameter 받는법

# urls.py
from django.urls import path

urlpatterns = [
    path('/test/<int:id>', Test1View.as_view()),
]
# view.py

class Test1View(View):
    def get(self, request, id):
        try:
            test1s = TestDB.objects.filter(id = id)

End Point : 127.0.0.1:8000/test/1

2. query parameter

  • 쿼리(질문)을 넣어 요청하여 통신하는 방법
  • search, filter 등의 요청을 GET methed를 활용하여 통신한다.

127.0.0.1:8000/products/list?theme=한식&sort=낮은가격순

  • 요청: theme라는 key의 value값을 '한식', sort라는 key의 value값을 '낮은가격순' 으로 filter해서 반환하라
# views.py
class ProductListView(View):
    def get(self, request):
        try:
            theme = request.GET.get('theme', None)
            sort = request.GET.get('sort', None)
             # GET메소드의 쿼리파라미터의 value값을 가져와 담아라

            sort_type= {
                "신메뉴순" : "-id",
                "높은가격순": "-price",
                "낮은가격순": "price"
            }
            themes = Theme.objects.get(theme=theme).id
            products = Product.objects.filter(producttheme__theme_id = themes).order_by(sort_type[sort])

위와 같이 파리미터로 조회요청을 하여 API에서 그 요청값을 받아 처리한뒤 response해준다.

profile
WEB Developer

0개의 댓글