[Django]ManyToManyField(feat.views.py)

Jimin_Note·2022년 6월 8일
0

🌱Django

목록 보기
9/13
post-thumbnail

🌱views.py

import json

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

from movies.models import Movie, Actor

class ActorView(View):
    def get(self, request):
        results=[]
        for actor in Actor.objects.all():
            results.append(
            {
                "name" : actor.first_name + actor.last_name,
                "movie list" : [ movie.title for movie in actor.movies.all()]
            }
        )
        return JsonResponse({'result':results}, status=200)

class MovieView(View):
    def get(self, request):
        results=[]
        for movie in Movie.objects.all():
            results.append(
            {
                "title" : movie.title,
                "running time" : movie.running_time,
                "actors" :  [movie.first_name + movie.last_name for movie in movie.actor_set.all()]
               
            }
        )
        return JsonResponse({'result':results}, status=200)
    
    
    

🌱httpie GET

http -v GET 127.0.0.1:8000/movies/actor

{
    "result": [
        {
            "movie list": [
                "브로커"
            ],
            "name": "이지은"
        },
        {
            "movie list": [
                "범죄도시2",
                "부라더"
            ],
            "name": "마동석"
        },
        {
            "movie list": [
                "브로커",
                "기생충"
            ],
            "name": "송강호"
        }
    ]
}

http -v GET 127.0.0.1:8000/movies/movie

{
    "result": [
        {
            "actors": [
                "이지은",
                "송강호"
            ],
            "running time": 129,
            "title": "브로커"
        },
        {
            "actors": [
                "송강호"
            ],
            "running time": 132,
            "title": "기생충"
        },
        {
            "actors": [
                "마동석"
            ],
            "running time": 106,
            "title": "범죄도시2"
        },
        {
            "actors": [
                "마동석"
            ],
            "running time": 102,
            "title": "부라더"
        }
    ]
}
profile
Hello. I'm jimin:)

0개의 댓글