TIL | Django | JSON 방식으로 View 작성하는 방법

이도운·2022년 1월 10일
0

TIL

목록 보기
39/73
post-thumbnail

create view

import json

from django.http import JsonResponse
from django.views import View

from products.models import Menu, Category, Product

class ProductsView(View):
    def post(self, request):
        data     = json.loads(request.body)
        menu     = Menu.objects.create(name=data['menu'])
        category = Category.objects.create(
            name = data['category'],
            menu = menu
        )
        Product.objects.create(
            name     = data['product'], 
            category = category,
            menu     = menu
        )
    return JsonResponse({'messasge':'created'}, status=201)

read view

import json

from django.http import JsonResponse
from django.views import View

from products.models import Menu, Category, Product

class ProductsView(View):
    def get(self, request):
        products = Product.objects.all()
        results  = []

       for product in products:
           results.append(
               {
                   "menu" : product.category.menu.name,
                   "category" : product.category.name,
                   "product_name" : product.name
               }
           )
       
        return JsonResponse({'resutls':results}, status=200)
profile
⌨️ 백엔드개발자 (컴퓨터공학과 졸업)

0개의 댓글