이번에는 지난번에 작성한 westarbucks model을 가지고 음료를 등록하고 조회하는 view를 작성해보려고 한다.
import json
from django.views import View
from django.http import JsonResponse
from products.models import Menu, Drink, Category
class ProductView(View):
def get(self, request):
# GET 127.0.0.1:8000
drinks = Drink.objects.all()
result = []
for drink in drinks:
result.append(
{
"korean_name": drink.korean_name,
"english_name": drink.english_name,
"description": drink.description,
"category": drink.category.name
}
)
print(f"results objects: {result}")
return JsonResponse({"drink": result}, status=200)
def post(self, request):
# POST 127.0.0.1:8000
data = json.loads(request.body)
category = Category.objects.get(name=data["category"])
drink = Drink.objects.create(
korean_name = data["korean_name"],
english_name = data["english_name"],
description = data["description"],
category_id = category.id
)
return JsonResponse({"message" : "SUCESS"}, status=201)