왓챠피디아 클론④API-Watchlist

박민하·2022년 7월 3일
0

PROJECT

목록 보기
13/17
post-thumbnail

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


✅ Model

✔ import

from django.db import models

from films.models import Film

✔ class: WatchList, Rate

class WatchList(models.Model):
    film = models.ForeignKey(Film, on_delete=models.CASCADE)
    user = models.ForeignKey('User', on_delete=models.CASCADE)

    class Meta:
        db_table = 'watch_lists'

class Rate(models.Model):
    score = models.DecimalField(max_digits=2, decimal_places=1)
    film  = models.ForeignKey(Film, on_delete=models.CASCADE)
    user  = models.ForeignKey('User', on_delete=models.CASCADE)

    class Meta:
        db_table = 'rates'

✅ Views

✔ import

import json

import bcrypt
import jwt
from django.http            import JsonResponse
from django.views           import View
from django.conf            import settings

from users.models     import WatchList
from films.models     import Film

✔ class: 보고싶어요

class WatchListView(View):
    @token_decorator
    def post(self, request):
        try:
            data = json.loads(request.body)

            if not Film.objects.filter(id = data['film_id']).exists:
                return JsonResponse({'message' : 'FILM_DOES_NOT_EXIST'}, status = 404)

            film = Film.objects.get(id = data['film_id'])
            user = request.user

            wish, is_created = WatchList.objects.get_or_create(film = film, user = user)

            if not is_created:
                wish.delete()
                return JsonResponse({'message' : 'WATCH_LIST_DELETED'}, status = 204)

            return JsonResponse({'message' : 'SUCCESS'}, status = 201)

        except KeyError:
            return JsonResponse({'message' :'KEY_ERROR'}, status = 400)

    @token_decorator
    def get(self, request):
        user = request.user
        sort = request.GET.get('sort')

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

        order_key = sort_set.get(sort, '-watchlist__id')

        films = Film.objects.filter(watchlist__user=user).order_by(order_key)

        results = [{
            'id'               : film.id,
            'name'             : film.name,
            'image_url'        : film.image_url
        } for film in films]
        return JsonResponse({'results': results}, status=200)

✔ class: 프로필 페이지

class UserView(View):
    @token_decorator
    def get(self, request):
        try:
            user = request.user

            results = {
                'username'        : user.username,
                'watchlist_count' : user.watchlist_set.count(),
            }
            return JsonResponse({'results' : results})

        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)

✅ Url

✔ import

from django.urls import path

from users.views import WatchListView, UserView

✔ urlpatterns

urlpatterns = [
    path('/watchlist', WatchListView.as_view()),
    path('', UserView.as_view())
]
profile
backend developer 🐌

0개의 댓글