From 2210a031d6176651f6a5faa3128c8285d3c69a3d Mon Sep 17 00:00:00 2001 From: Stepan Date: Fri, 27 Sep 2024 22:54:12 +0300 Subject: [PATCH 1/9] add Actor, Genre, CinemaHall to models & update Movie --- cinema/models.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cinema/models.py b/cinema/models.py index cc477513f..3bec2fec9 100644 --- a/cinema/models.py +++ b/cinema/models.py @@ -1,10 +1,36 @@ from django.db import models +class Genre(models.Model): + name = models.CharField(max_length=255, unique=True) + + def __str__(self) -> str: + return self.name + + +class Actor(models.Model): + first_name = models.CharField(max_length=255) + last_name = models.CharField(max_length=255) + + def __str__(self) -> str: + return f"{self.first_name} {self.last_name}" + + +class CinemaHall(models.Model): + name = models.CharField(max_length=255) + rows = models.IntegerField() + seats_in_row = models.IntegerField() + + def __str__(self) -> str: + return f"{self.name}: rows - {self.rows}, seats - {self.seats_in_row}" + + class Movie(models.Model): title = models.CharField(max_length=255) description = models.TextField() duration = models.IntegerField() + actors = models.ManyToManyField(Actor, related_name="movies") + genres = models.ManyToManyField(Genre, related_name="movies") def __str__(self): return self.title From c9f0e2ec470748385efcf5c710918f7deb80ffc6 Mon Sep 17 00:00:00 2001 From: Stepan Date: Fri, 27 Sep 2024 22:55:02 +0300 Subject: [PATCH 2/9] add ActorSerializer, GenreSerializer, CinemaHallSerializer to serializers.py & update MovieSerializer --- cinema/serializers.py | 47 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/cinema/serializers.py b/cinema/serializers.py index 050db5771..74d10b1b2 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -1,6 +1,6 @@ from rest_framework import serializers -from cinema.models import Movie +from cinema.models import Movie, Actor, Genre, CinemaHall class MovieSerializer(serializers.Serializer): @@ -8,17 +8,56 @@ class MovieSerializer(serializers.Serializer): title = serializers.CharField(max_length=255) description = serializers.CharField() duration = serializers.IntegerField() + actors = serializers.PrimaryKeyRelatedField( + queryset=Actor.objects.all(), + many=True, + ) + genres = serializers.PrimaryKeyRelatedField( + queryset=Genre.objects.all(), + many=True, + ) - def create(self, validated_data): - return Movie.objects.create(**validated_data) + def create(self, validated_data: dict) -> Movie: + actors = validated_data.pop("actors", []) + genres = validated_data.pop("genres", []) + movie = Movie.objects.create(**validated_data) + movie.actors.set(actors) + movie.genres.set(genres) + return movie - def update(self, instance, validated_data): + def update(self, instance: Movie, validated_data: dict) -> Movie: instance.title = validated_data.get("title", instance.title) instance.description = validated_data.get( "description", instance.description ) instance.duration = validated_data.get("duration", instance.duration) + actors = validated_data.get("actors", None) + genres = validated_data.get("genres", None) + + if actors: + instance.actors.set(actors) + + if genres: + instance.genres.set(genres) instance.save() return instance + + +class ActorSerializer(serializers.ModelSerializer): + class Meta: + model = Actor + fields = ["first_name", "last_name"] + + +class GenreSerializer(serializers.ModelSerializer): + class Meta: + model = Genre + fields = ["name"] + + +class CinemaHallSerializer(serializers.ModelSerializer): + class Meta: + model = CinemaHall + fields = ["name", "rows", "seats_in_row"] From 488fceadc5400ab53a1577d87ec203542f0e39f5 Mon Sep 17 00:00:00 2001 From: Stepan Date: Fri, 27 Sep 2024 22:56:08 +0300 Subject: [PATCH 3/9] add view for Actor, Genre, Movie, CinemaHall --- cinema/views.py | 124 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 95 insertions(+), 29 deletions(-) diff --git a/cinema/views.py b/cinema/views.py index 78ba8a79c..0848f3d8c 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -1,45 +1,111 @@ -from rest_framework.decorators import api_view +from django.core.serializers import serialize +from django.http import HttpRequest from rest_framework.response import Response -from rest_framework import status +from rest_framework import status, viewsets, mixins, generics from django.shortcuts import get_object_or_404 +from rest_framework.views import APIView -from cinema.models import Movie -from cinema.serializers import MovieSerializer +from cinema.models import Movie, Genre, Actor, CinemaHall +from cinema.serializers import ( + MovieSerializer, + GenreSerializer, + ActorSerializer, + CinemaHallSerializer, +) -@api_view(["GET", "POST"]) -def movie_list(request): - if request.method == "GET": - movies = Movie.objects.all() - serializer = MovieSerializer(movies, many=True) +class GenreList(APIView): + def get(self, request: HttpRequest) -> Response: + genre = Genre.objects.all() + serializer = GenreSerializer(genre, many=True) return Response(serializer.data, status=status.HTTP_200_OK) - if request.method == "POST": - serializer = MovieSerializer(data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_201_CREATED) + def post(self, request: HttpRequest) -> Response: + serializer = GenreSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +class GenreDetail(APIView): + def get_object(self, pk: int) -> Genre: + return get_object_or_404(Genre, pk=pk) -@api_view(["GET", "PUT", "DELETE"]) -def movie_detail(request, pk): - movie = get_object_or_404(Movie, pk=pk) - - if request.method == "GET": - serializer = MovieSerializer(movie) + def get(self, request: HttpRequest, pk: int) -> Response: + genre = self.get_object(pk) + serializer = GenreSerializer(genre) return Response(serializer.data, status=status.HTTP_200_OK) - if request.method == "PUT": - serializer = MovieSerializer(movie, data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) + def put(self, request: HttpRequest, pk: int) -> Response: + genre = self.get_object(pk) + serializer = GenreSerializer(genre, data=request.data) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + def patch(self, request: HttpRequest, pk: int) -> Response: + genre = self.get_object(pk) + serializer = GenreSerializer(genre, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data) - if request.method == "DELETE": - movie.delete() + def delete(self, request: HttpRequest, pk: int) -> Response: + genre = self.get_object(pk) + genre.delete() return Response(status=status.HTTP_204_NO_CONTENT) + + +class ActorList( + mixins.ListModelMixin, + mixins.CreateModelMixin, + generics.GenericAPIView +): + queryset = Actor.objects.all() + serializer_class = ActorSerializer + + def get(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.list(request, *args, **kwargs) + + def post(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.create(request, *args, **kwargs) + + +class ActorDetail( + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + generics.GenericAPIView, +): + queryset = Actor.objects.all() + serializer_class = ActorSerializer + + def get(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.retrieve(request, *args, **kwargs) + + def put(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.update(request, *args, **kwargs) + + def patch(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.partial_update(request, *args, **kwargs) + + def delete(self, request: HttpRequest, *args, **kwargs) -> Response: + return self.destroy(request, *args, **kwargs) + + +class CinemaHallViewSet( + mixins.ListModelMixin, + mixins.CreateModelMixin, + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + viewsets.GenericViewSet +): + queryset = CinemaHall.objects.all() + serializer_class = CinemaHallSerializer + + +class MovieViewSet(viewsets.ModelViewSet): + queryset = Movie.objects.all() + serializer_class = MovieSerializer From 5e2bd6b64e1380fa4d121f17f2b90e6190148536 Mon Sep 17 00:00:00 2001 From: Stepan Date: Fri, 27 Sep 2024 22:56:23 +0300 Subject: [PATCH 4/9] update urls --- ...emahall_genre_movie_actors_movie_genres.py | 50 +++++++++++++++++++ ...move_movie_genres_movie_actors_and_more.py | 31 ++++++++++++ cinema/urls.py | 46 +++++++++++++++-- 3 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py create mode 100644 cinema/migrations/0003_remove_movie_actors_remove_movie_genres_movie_actors_and_more.py diff --git a/cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py b/cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py new file mode 100644 index 000000000..ee35c59c6 --- /dev/null +++ b/cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py @@ -0,0 +1,50 @@ +# Generated by Django 4.1 on 2024-09-27 17:23 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('cinema', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Actor', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(max_length=255)), + ('last_name', models.CharField(max_length=255)), + ], + ), + migrations.CreateModel( + name='CinemaHall', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('rows', models.IntegerField()), + ('seats_in_row', models.IntegerField()), + ], + ), + migrations.CreateModel( + name='Genre', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True)), + ], + ), + migrations.AddField( + model_name='movie', + name='actors', + field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='movies', to='cinema.actor'), + preserve_default=False, + ), + migrations.AddField( + model_name='movie', + name='genres', + field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='movies', to='cinema.genre'), + preserve_default=False, + ), + ] diff --git a/cinema/migrations/0003_remove_movie_actors_remove_movie_genres_movie_actors_and_more.py b/cinema/migrations/0003_remove_movie_actors_remove_movie_genres_movie_actors_and_more.py new file mode 100644 index 000000000..8370ed381 --- /dev/null +++ b/cinema/migrations/0003_remove_movie_actors_remove_movie_genres_movie_actors_and_more.py @@ -0,0 +1,31 @@ +# Generated by Django 4.1 on 2024-09-27 17:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('cinema', '0002_actor_cinemahall_genre_movie_actors_movie_genres'), + ] + + operations = [ + migrations.RemoveField( + model_name='movie', + name='actors', + ), + migrations.RemoveField( + model_name='movie', + name='genres', + ), + migrations.AddField( + model_name='movie', + name='actors', + field=models.ManyToManyField(related_name='movies', to='cinema.actor'), + ), + migrations.AddField( + model_name='movie', + name='genres', + field=models.ManyToManyField(related_name='movies', to='cinema.genre'), + ), + ] diff --git a/cinema/urls.py b/cinema/urls.py index 1ae7d5cb0..ee1e1bee2 100644 --- a/cinema/urls.py +++ b/cinema/urls.py @@ -1,10 +1,48 @@ -from django.urls import path +from django.urls import path, include +from rest_framework import routers -from cinema.views import movie_list, movie_detail +from cinema.views import ( + MovieViewSet, + GenreList, + GenreDetail, + ActorList, + ActorDetail, + CinemaHallViewSet, +) + +router = routers.DefaultRouter() + +router.register("movies", MovieViewSet) + +cinema_hall_list = CinemaHallViewSet.as_view( + actions={ + "get": "list", + "post": "create", + } +) + +cinema_hall_detail = CinemaHallViewSet.as_view( + actions={ + "get": "retrieve", + "put": "update", + "patch": "partial_update", + "delete": "destroy", + } +) urlpatterns = [ - path("movies/", movie_list, name="movie-list"), - path("movies//", movie_detail, name="movie-detail"), + path("", include(router.urls)), + path("actors/", ActorList.as_view(), name="actors-list"), + path("actors//", ActorDetail.as_view(), name="actors-detail"), + path("genres/", GenreList.as_view(), name="genres-list"), + path("genres//", GenreDetail.as_view(), name="genres-detail"), + path("cinema_halls/", cinema_hall_list, name="cinema_halls-list"), + path( + "cinema_halls//", + cinema_hall_detail, + name="cinema_halls-detail" + ), + ] app_name = "cinema" From 5d1f33a74e4e46987f25b2089338ae40bfc9aff1 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 29 Sep 2024 18:47:05 +0300 Subject: [PATCH 5/9] add help_text to duration field --- cinema/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cinema/models.py b/cinema/models.py index 3bec2fec9..de97a6657 100644 --- a/cinema/models.py +++ b/cinema/models.py @@ -28,7 +28,7 @@ def __str__(self) -> str: class Movie(models.Model): title = models.CharField(max_length=255) description = models.TextField() - duration = models.IntegerField() + duration = models.IntegerField(help_text="Duration in minutes") actors = models.ManyToManyField(Actor, related_name="movies") genres = models.ManyToManyField(Genre, related_name="movies") From 3a6fabe42e213a208059e17d801323ab4fef7c33 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 29 Sep 2024 18:47:22 +0300 Subject: [PATCH 6/9] update imports in serializers.py & views.py --- cinema/serializers.py | 7 ++++++- cinema/views.py | 15 ++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/cinema/serializers.py b/cinema/serializers.py index 74d10b1b2..7bf257f95 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -1,6 +1,11 @@ from rest_framework import serializers -from cinema.models import Movie, Actor, Genre, CinemaHall +from cinema.models import ( + Movie, + Actor, + Genre, + CinemaHall +) class MovieSerializer(serializers.Serializer): diff --git a/cinema/views.py b/cinema/views.py index 0848f3d8c..82f698c8d 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -1,12 +1,21 @@ -from django.core.serializers import serialize from django.http import HttpRequest from rest_framework.response import Response -from rest_framework import status, viewsets, mixins, generics +from rest_framework import ( + status, + viewsets, + mixins, + generics, +) from django.shortcuts import get_object_or_404 from rest_framework.views import APIView -from cinema.models import Movie, Genre, Actor, CinemaHall +from cinema.models import ( + Movie, + Genre, + Actor, + CinemaHall, +) from cinema.serializers import ( MovieSerializer, GenreSerializer, From 4f7e4aada34767b843b074def68878ebaf40bd68 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 29 Sep 2024 18:47:55 +0300 Subject: [PATCH 7/9] add blank line after imports --- cinema/urls.py | 1 + 1 file changed, 1 insertion(+) diff --git a/cinema/urls.py b/cinema/urls.py index ee1e1bee2..832bb9648 100644 --- a/cinema/urls.py +++ b/cinema/urls.py @@ -10,6 +10,7 @@ CinemaHallViewSet, ) + router = routers.DefaultRouter() router.register("movies", MovieViewSet) From 7810fbca7c28cc611b659bff41931fa2603a1763 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 29 Sep 2024 18:52:46 +0300 Subject: [PATCH 8/9] change MovieSerializer to inherit ModelSerializer --- cinema/serializers.py | 51 ++++++++++--------------------------------- 1 file changed, 12 insertions(+), 39 deletions(-) diff --git a/cinema/serializers.py b/cinema/serializers.py index 7bf257f95..883fa0ae9 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -8,46 +8,19 @@ ) -class MovieSerializer(serializers.Serializer): - id = serializers.IntegerField(read_only=True) - title = serializers.CharField(max_length=255) - description = serializers.CharField() - duration = serializers.IntegerField() - actors = serializers.PrimaryKeyRelatedField( - queryset=Actor.objects.all(), - many=True, - ) - genres = serializers.PrimaryKeyRelatedField( - queryset=Genre.objects.all(), - many=True, - ) +class MovieSerializer(serializers.ModelSerializer): + actors = serializers.StringRelatedField(many=True) + genres = serializers.StringRelatedField(many=True) - def create(self, validated_data: dict) -> Movie: - actors = validated_data.pop("actors", []) - genres = validated_data.pop("genres", []) - movie = Movie.objects.create(**validated_data) - movie.actors.set(actors) - movie.genres.set(genres) - return movie - - def update(self, instance: Movie, validated_data: dict) -> Movie: - instance.title = validated_data.get("title", instance.title) - instance.description = validated_data.get( - "description", instance.description - ) - instance.duration = validated_data.get("duration", instance.duration) - actors = validated_data.get("actors", None) - genres = validated_data.get("genres", None) - - if actors: - instance.actors.set(actors) - - if genres: - instance.genres.set(genres) - - instance.save() - - return instance + class Meta: + model = Movie + fields = [ + "title", + "description", + "duration", + "actors", + "genres", + ] class ActorSerializer(serializers.ModelSerializer): From ad3bdda9a7d7d363869d3e964533692a9e5d3f03 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 29 Sep 2024 19:18:15 +0300 Subject: [PATCH 9/9] update ActorList & ActorDetail --- cinema/views.py | 28 +++------------------------- 1 file changed, 3 insertions(+), 25 deletions(-) diff --git a/cinema/views.py b/cinema/views.py index 82f698c8d..aa3c336b5 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -67,41 +67,19 @@ def delete(self, request: HttpRequest, pk: int) -> Response: class ActorList( - mixins.ListModelMixin, - mixins.CreateModelMixin, - generics.GenericAPIView + generics.ListAPIView, + generics.CreateAPIView ): queryset = Actor.objects.all() serializer_class = ActorSerializer - def get(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.list(request, *args, **kwargs) - - def post(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.create(request, *args, **kwargs) - class ActorDetail( - mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.DestroyModelMixin, - generics.GenericAPIView, + generics.RetrieveUpdateDestroyAPIView, ): queryset = Actor.objects.all() serializer_class = ActorSerializer - def get(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.retrieve(request, *args, **kwargs) - - def put(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.update(request, *args, **kwargs) - - def patch(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.partial_update(request, *args, **kwargs) - - def delete(self, request: HttpRequest, *args, **kwargs) -> Response: - return self.destroy(request, *args, **kwargs) - class CinemaHallViewSet( mixins.ListModelMixin,