왓챠피디아 클론③API-Films

박민하·2022년 7월 3일
0

PROJECT

목록 보기
12/17
post-thumbnail

<Watcha_classic>
클래식 영화 모음 사이트.
영화 정보를 확인거나, 영화를 유저의 프로필 페이지에 삭제/등록 할 수 있다.


✅ Model

✔ import

from django.db import models

✔ class: 영화/감독/배우 정보

class Film(models.Model):
    name             = models.CharField(max_length=100)
    release_date     = models.DateField()
    image_url        = models.CharField(max_length=1000, default='')
    running_time_min = models.IntegerField()
    description      = models.CharField(max_length=1000, default='')
    rating_system    = models.ForeignKey('RatingSystem', on_delete=models.CASCADE)

    class Meta:
        db_table = 'films'

class RatingSystem(models.Model):
    rate = models.CharField(max_length=50, default='')

    class Meta:
        db_table = 'rating_systems'

class Genre(models.Model):
    name  = models.CharField(max_length=50)
    film  = models.ManyToManyField(Film, through='FilmGenre', related_name='genres')

    class Meta:
        db_table = 'genres'

class Director(models.Model):
    name      = models.CharField(max_length=80)
    image_url = models.CharField(max_length=1000, default='')
    film      = models.ManyToManyField(Film, through='FilmDirector', related_name='directors')

    class Meta:
        db_table = 'directors'

class Actor(models.Model):
    name      = models.CharField(max_length=80)
    image_url = models.CharField(max_length=1000, default='')
    film      = models.ManyToManyField(Film, through='FilmActor', related_name='actors')

    class Meta:
        db_table = 'actors'

class Cast(models.Model):
    name = models.CharField(max_length=80, default='')

    class Meta:
        db_table = 'casts'

class Role(models.Model):
    name = models.CharField(max_length=80, default='')

    class Meta:
        db_table = 'roles'

class OttPlatform(models.Model):
    name  = models.CharField(max_length=50, default='')
    film  = models.ManyToManyField(Film, through='FilmOttPlatForm', related_name='ott_platforms')

    class Meta:
        db_table = 'ott_platforms'

class Country(models.Model):
    name  = models.CharField(max_length=50)
    film  = models.ManyToManyField(Film, through='FilmCountry', related_name='countries')

    class Meta:
        db_table = 'countries'

class FilmGenre(models.Model):
    film  = models.ForeignKey('Film', on_delete=models.CASCADE)
    genre = models.ForeignKey('Genre', on_delete=models.CASCADE)

    class Meta:
        db_table = 'films_genres'

class FilmDirector(models.Model):
    film     = models.ForeignKey('Film', on_delete=models.CASCADE)
    director = models.ForeignKey('Director', on_delete=models.CASCADE)

    class Meta:
        db_table = 'films_directors'

class FilmActor(models.Model):
    film  = models.ForeignKey('Film', on_delete=models.CASCADE)
    actor = models.ForeignKey('Actor', on_delete=models.CASCADE)
    cast  = models.ForeignKey('Cast', on_delete=models.CASCADE, null=True)
    role  = models.ForeignKey('Role', on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'films_actors'

class FilmOttPlatform(models.Model):
    film         = models.ForeignKey('Film', on_delete=models.CASCADE)
    ott_platform = models.ForeignKey('OttPlatform', on_delete=models.CASCADE)

    class Meta:
        db_table = 'films_ott_platforms'

class FilmCountry(models.Model):
    film    = models.ForeignKey('Film', on_delete=models.CASCADE)
    country = models.ForeignKey('Country', on_delete=models.CASCADE)

    class Meta:
        db_table = 'films_countries'

✅ Views

✔ import

from django.http      import JsonResponse
from django.views     import View
from django.db.models import Q

from films.models import Film

✔ class: 메인페이지

class FilmView(View):
    def get(self, request):
        try:
            genre            = request.GET.get('genre', None)
            country          = request.GET.get('country', None)
            running_time_min = request.GET.get('time', None)

            sort   = request.GET.get('sort')
            offset = int(request.GET.get('offset', 0))
            limit  = int(request.GET.get('limit', 10))

            q = Q()

            if genre:
                q &= Q(genres__name = genre)

            if country:
                q &= Q(countries__name = country)

            if running_time_min:
                q &= Q(running_time_min__lte = int(running_time_min))

            sort_set = {
                'random'          : '?',
                'score'           : 'rate_set__score',
                'time-ascending'  : 'running_time_min',
                'time-descending' : '-running_time_min',
            }

            order_key = sort_set.get(sort, 'id')

            films = Film.objects.filter(q).order_by(order_key)[offset:offset+limit]

            results = [{
                    'id'               : film.id,
                    'name'             : film.name,
                    'release_date'     : film.release_date.year,
                    'image_url'        : film.image_url,
                    'country'          : [country.name for country in film.countries.all()],
                    'running_time_min' : film.running_time_min,
                } for film in films]
            return JsonResponse({'results' : results}, status = 200)
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)

✔ class: 상세페이지

class FilmDetailView(View):
    def get(self, request, film_id):
        try:
            film    = Film.objects.get(id=film_id)
            results = {
                'id'               : film.id,
                'name'             : film.name,
                'release_date'     : film.release_date.year,
                'image_url'        : film.image_url,
                'running_time_min' : film.running_time_min,
                'descriptions'     : film.description,
                'genre'            : [genre.name for genre in film.genres.all()],
                'countries'        : [country.name for country in film.countries.all()],
                'directors' : [
                    {
                        'name'      : director.name,
                        'image_url' : director.image_url,
                        'role'      : '감독'
                    } for director in film.directors.all()
                ],
                'actors' : [
                    {
                        'name'      : actor.actor.name,
                        'image_url' : actor.actor.image_url,
                        'cast'      : actor.cast.name if actor.cast else None,
                        'role'      : actor.role.name
                    } for actor in film.filmactor_set.all()
                ]
            }
            return JsonResponse({'results': results}, status=200)
        except Film.DoesNotExist:
            return JsonResponse({'message': 'FILM_DOES_NOT_EXIST'}, status=400)

✅ Url

✔ import

from django.urls import path

from films.views import FilmView, FilmDetailView

✔ urlpatterns

urlpatterns = [
    path('', FilmView.as_view()),
    path('/<int:film_id>', FilmDetailView.as_view()),
]
profile
backend developer 🐌

0개의 댓글