[VIEW]Code Refactoring

박민하·2022년 6월 28일
0

DJANGO

목록 보기
14/22
post-thumbnail

왓챠피디아 클론 코딩에서 따온 코드.


✅ Before:

import json

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

from films.models import (
    Film, RatingSystem, Genre, Director, Actor, Cast, Role, OttPlatform, Country,
    FilmGenre, FilmDirector, FilmActor, FilmCountry
    )

class FilmDetailView(View):
    def get(self, request, film_id):
        try:
            films = Film.objects.get(id=film_id)
            rating_systems = RatingSystem.objects.get(id=films.rating_system_id)
            films_genres = FilmGenre.objects.filter(film_id=film_id)
            genres = [Genre.objects.get(id=i.genre_id).name for i in films_genres]
            films_directors = FilmDirector.objects.filter(film_id=film_id)[0]
            films_actors = FilmActor.objects.filter(film_id=film_id)
            film_countries = FilmCountry.objects.filter(film_id=film_id)
            countries = [Country.objects.get(id=i.id).name for i in film_countries]

            film = {
                'id' : films.id,
                'name' : films.name,
                'release_date' : films.release_date.year,
                'image_url' : films.image_url,
                'running_time_min' : films.running_time_min,
                'descriptions' : films.description,
                'genres' : genres,
                'directors' : {
                    'name' : Director.objects.get(id=films_directors.director_id).name,
                    'image_url' : Director.objects.get(id=films_directors.director_id).image_url,
                    'roles' : '감독'
                },
                'countries' : countries,
                'actors' : [
                    {
                        'name' : Actor.objects.get(id=i.actor_id).name,
                        'image_url' : Actor.objects.get(id=i.actor_id).image_url,
                        'cast' : i.cast.name if i.cast else None,
                        'role' : Role.objects.get(id=i.role_id).name
                    } for i in FilmActor.objects.filter(film_id=film_id)
                ]
            }
            rate = {
                'rating_systems' : rating_systems.rate
            }
            return JsonResponse({'film': film, 'rate':rate}, status=200)
        except KeyError:
            return JsonResponse({'message': 'KEYERROR'}, status=400)
        except Film.DoesNotExist:
            return JsonResponse({'message': 'FILM_DOES_NOT_EXIST'}, status=400)

✅ After:

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

from films.models import Film

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)

✅ 수정사항

✔ films

  film 객체 하나면 들고오니까 변수명을 단수로 수정

films = Film.objects.get(id=film_id)

film = Film.objects.get(id=film_id)

✔ genres

  같은 결과가 도출되는데 장황한 코드를 쓴 부분 수정, 이후에 이미 film 변수로 불러온 경로를 사용한 코드로 수정. 변수명은 단수로 변경. for문 쓸 때 변수명도 단수로 변경.

genres = [Genre.objects.get(id=i.genre_id).name for i in films_genres]

genres = [films_genres.genre.name for firms_genres in films_genres]

genre = [genre.genre.name for genre in film.genres.all()]

✔ directors

  film 테이블에서 directors를 불러와서 코드 단축.

for director in film.directors.all()

✔ 'role' : '감독'

  테이블을 수정하기에는 시간이 촉박해서 보류. 다음부터 하드코딩은 최대한 피하자!

✔ countries

  변수 두개를 설정했던걸 짧게 수정. 변수명 i는 코드 내용을 직관적으로 파악하기 어려워 country로 수정. film 테이블에서 countries를 모두 불러와서 코드 단축.

film_countries = FilmCountry.objects.filter(film_id=film_id)
countries = [Country.objects.get(id=i.id)name for i in film_countries]

'countries' : [country.name for country in film.countries.all()]

profile
backend developer 🐌

0개의 댓글