From d3fa906106a118cb2166c02bbf8680649d5d42e6 Mon Sep 17 00:00:00 2001 From: Denis Komandyr Date: Thu, 30 Nov 2023 02:20:26 +0200 Subject: [PATCH 1/5] Explore API view sets --- cinema/migrations/0001_initial.py | 1 - ...emahall_genre_movie_actors_movie_genres.py | 70 ++++++++++++ cinema/models.py | 26 +++++ cinema/serializers.py | 77 ++++++++++++- cinema/urls.py | 40 ++++++- cinema/views.py | 105 ++++++++++++++---- 6 files changed, 289 insertions(+), 30 deletions(-) create mode 100644 cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py diff --git a/cinema/migrations/0001_initial.py b/cinema/migrations/0001_initial.py index 514947a64..8f0b180c1 100644 --- a/cinema/migrations/0001_initial.py +++ b/cinema/migrations/0001_initial.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - initial = True dependencies = [] 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..d9e98ec55 --- /dev/null +++ b/cinema/migrations/0002_actor_cinemahall_genre_movie_actors_movie_genres.py @@ -0,0 +1,70 @@ +# Generated by Django 4.1 on 2023-11-29 23:08 + +from django.db import migrations, models + + +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.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/models.py b/cinema/models.py index cc477513f..a577d6e90 100644 --- a/cinema/models.py +++ b/cinema/models.py @@ -1,9 +1,35 @@ from django.db import models +class Genre(models.Model): + name = models.CharField(max_length=255, unique=True) + + def __str__(self): + return self.name + + +class Actor(models.Model): + first_name = models.CharField(max_length=255) + last_name = models.CharField(max_length=255) + + def __str__(self): + 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): + return self.name + + class Movie(models.Model): title = models.CharField(max_length=255) description = models.TextField() + actors = models.ManyToManyField(Actor, related_name="movies") + genres = models.ManyToManyField(Genre, related_name="movies") duration = models.IntegerField() def __str__(self): diff --git a/cinema/serializers.py b/cinema/serializers.py index 050db5771..ca2bcd7d9 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -1,16 +1,79 @@ from rest_framework import serializers -from cinema.models import Movie +from cinema.models import Movie, Genre, Actor, CinemaHall + + +class GenreSerializer(serializers.Serializer): + id = serializers.IntegerField(read_only=True) + name = serializers.CharField(max_length=255) + + def create(self, validated_data): + return Genre.objects.create(**validated_data) + + def update(self, instance, validated_data): + instance.name = validated_data.get("name", instance.name) + instance.save() + return instance + + +class ActorSerializer(serializers.Serializer): + id = serializers.IntegerField(read_only=True) + first_name = serializers.CharField(max_length=255) + last_name = serializers.CharField(max_length=255) + + def create(self, validated_data): + return Actor.objects.create(**validated_data) + + def update(self, instance, validated_data): + instance.first_name = validated_data.get( + "first_name", instance.first_name + ) + instance.last_name = validated_data.get( + "last_name", instance.last_name + ) + instance.save() + return instance + + +class CinemaHallSerializer(serializers.Serializer): + id = serializers.IntegerField(read_only=True) + name = serializers.CharField(max_length=255) + rows = serializers.IntegerField() + seats_in_row = serializers.IntegerField() + + def create(self, validated_data): + return CinemaHall.objects.create(**validated_data) + + def update(self, instance, validated_data): + instance.name = validated_data.get("name", instance.name) + instance.rows = validated_data.get("rows", instance.rows) + instance.seats_in_row = validated_data.get( + "seats_in_row", instance.seats_in_row + ) + instance.save() + return instance class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(max_length=255) description = serializers.CharField() + actors = ActorSerializer(many=True) + genres = GenreSerializer(many=True) duration = serializers.IntegerField() def create(self, validated_data): - return Movie.objects.create(**validated_data) + actors_data = validated_data.pop("actors") + genres_data = validated_data.pop("genres") + movie = Movie.objects.create(**validated_data) + for actor_data in actors_data: + actor, _ = Actor.objects.get_or_create(**actor_data) + movie.actors.add(actor) + for genre_data in genres_data: + genre, _ = Genre.objects.get_or_create(**genre_data) + movie.gernes.add(genre) + + return movie def update(self, instance, validated_data): instance.title = validated_data.get("title", instance.title) @@ -18,6 +81,16 @@ def update(self, instance, validated_data): "description", instance.description ) instance.duration = validated_data.get("duration", instance.duration) + actors_data = validated_data.pop("actors") + genres_data = validated_data.pop("genres") + instance.actors.clear() + instance.genres.clear() + for actor_data in actors_data: + actor, _ = Actor.objects.get_or_create(**actor_data) + instance.actors.add(actor) + for genre_data in genres_data: + genre, _ = Genre.objects.get_or_create(**genre_data) + instance.genres.add(genre) instance.save() diff --git a/cinema/urls.py b/cinema/urls.py index 1ae7d5cb0..4475aa7b3 100644 --- a/cinema/urls.py +++ b/cinema/urls.py @@ -1,10 +1,42 @@ -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 ( + GenreList, + GenreDetail, + ActorList, + ActorDetail, + CinemaHallViewSet, + MovieViewSet, +) + +cinema_hall_list = CinemaHallViewSet.as_view( + actions={"get": "list", "post": "create"} +) +cinema_hall_detail = CinemaHallViewSet.as_view( + { + "get": "retrieve", + "put": "update", + "patch": "partial_update", + "delete": "destroy" + } +) + +router = routers.DefaultRouter() +router.register("movies", MovieViewSet) urlpatterns = [ - path("movies/", movie_list, name="movie-list"), - path("movies//", movie_detail, name="movie-detail"), + path("genres/", GenreList.as_view(), name="genre-list"), + path("genres//", GenreDetail.as_view(), name="genre-detail"), + path("cinema_halls/", cinema_hall_list, name="cinema-hall-list"), + path( + "cinema_halls//", + cinema_hall_detail, + name="cinema-hall-detail" + ), + path("actors/", ActorList.as_view(), name="actor-list"), + path("actors//", ActorDetail.as_view(), name="actor-detail"), + path("", include(router.urls)), ] app_name = "cinema" diff --git a/cinema/views.py b/cinema/views.py index 78ba8a79c..d9dd1aca5 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -1,45 +1,104 @@ +from django.http import Http404 from rest_framework.decorators import api_view from rest_framework.response import Response -from rest_framework import status +from rest_framework import status, mixins, generics, viewsets 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): + genres = Genre.objects.prefetch_related("movies").all() + serializer = GenreSerializer(genres, many=True) return Response(serializer.data, status=status.HTTP_200_OK) - if request.method == "POST": - serializer = MovieSerializer(data=request.data) + def post(self, request): + serializer = GenreSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -@api_view(["GET", "PUT", "DELETE"]) -def movie_detail(request, pk): - movie = get_object_or_404(Movie, pk=pk) +class GenreDetail(APIView): + def get_object(self, pk): + try: + return Genre.objects.get(pk=pk) + except Genre.DoesNotExist: + raise Http404 - if request.method == "GET": - serializer = MovieSerializer(movie) - return Response(serializer.data, status=status.HTTP_200_OK) + def get(self, request, pk): + genre = self.get_object(pk) + serializer = GenreSerializer(genre) + return Response(serializer.data) - if request.method == "PUT": - serializer = MovieSerializer(movie, data=request.data) + def put(self, request, pk): + genre = self.get_object(pk) + serializer = GenreSerializer(genre, data=request.data) if serializer.is_valid(): serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - + return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - if request.method == "DELETE": - movie.delete() + def delete(self, request, pk): + 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.prefetch_related("movies").all() + serializer_class = ActorSerializer + + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) + + +class ActorDetail( + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + generics.GenericAPIView, +): + queryset = Actor.objects.prefetch_related("movies").all() + serializer_class = ActorSerializer + + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) + + def delete(self, request, *args, **kwargs): + 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.prefetch_related("actors", "genres").all() + serializer_class = MovieSerializer From ebea25c6f13c034972a4ce0fe77a22878a6e3692 Mon Sep 17 00:00:00 2001 From: Denis Komandyr Date: Thu, 30 Nov 2023 02:53:45 +0200 Subject: [PATCH 2/5] Hotfix required field and add patch methods to genres and actors views --- ...3_alter_movie_actors_alter_movie_genres.py | 26 ++++++++++++++ cinema/models.py | 4 +-- cinema/serializers.py | 34 +++++++------------ cinema/views.py | 13 +++++-- 4 files changed, 51 insertions(+), 26 deletions(-) create mode 100644 cinema/migrations/0003_alter_movie_actors_alter_movie_genres.py diff --git a/cinema/migrations/0003_alter_movie_actors_alter_movie_genres.py b/cinema/migrations/0003_alter_movie_actors_alter_movie_genres.py new file mode 100644 index 000000000..b613316c6 --- /dev/null +++ b/cinema/migrations/0003_alter_movie_actors_alter_movie_genres.py @@ -0,0 +1,26 @@ +# Generated by Django 4.1 on 2023-11-30 00:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("cinema", "0002_actor_cinemahall_genre_movie_actors_movie_genres"), + ] + + operations = [ + migrations.AlterField( + model_name="movie", + name="actors", + field=models.ManyToManyField( + blank=True, related_name="movies", to="cinema.actor" + ), + ), + migrations.AlterField( + model_name="movie", + name="genres", + field=models.ManyToManyField( + blank=True, related_name="movies", to="cinema.genre" + ), + ), + ] diff --git a/cinema/models.py b/cinema/models.py index a577d6e90..50b832a87 100644 --- a/cinema/models.py +++ b/cinema/models.py @@ -28,8 +28,8 @@ def __str__(self): class Movie(models.Model): title = models.CharField(max_length=255) description = models.TextField() - actors = models.ManyToManyField(Actor, related_name="movies") - genres = models.ManyToManyField(Genre, related_name="movies") + actors = models.ManyToManyField(Actor, related_name="movies", blank=True) + genres = models.ManyToManyField(Genre, related_name="movies", blank=True) duration = models.IntegerField() def __str__(self): diff --git a/cinema/serializers.py b/cinema/serializers.py index ca2bcd7d9..d6cd98bc2 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -58,20 +58,16 @@ class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(max_length=255) description = serializers.CharField() - actors = ActorSerializer(many=True) - genres = GenreSerializer(many=True) + actors = ActorSerializer(many=True, required=False) + genres = GenreSerializer(many=True, required=False) duration = serializers.IntegerField() def create(self, validated_data): - actors_data = validated_data.pop("actors") - genres_data = validated_data.pop("genres") + actors_data = validated_data.pop("actors", []) + genres_data = validated_data.pop("genres", []) movie = Movie.objects.create(**validated_data) - for actor_data in actors_data: - actor, _ = Actor.objects.get_or_create(**actor_data) - movie.actors.add(actor) - for genre_data in genres_data: - genre, _ = Genre.objects.get_or_create(**genre_data) - movie.gernes.add(genre) + movie.actors.set(actors_data) + movie.genres.set(genres_data) return movie @@ -81,17 +77,11 @@ def update(self, instance, validated_data): "description", instance.description ) instance.duration = validated_data.get("duration", instance.duration) - actors_data = validated_data.pop("actors") - genres_data = validated_data.pop("genres") - instance.actors.clear() - instance.genres.clear() - for actor_data in actors_data: - actor, _ = Actor.objects.get_or_create(**actor_data) - instance.actors.add(actor) - for genre_data in genres_data: - genre, _ = Genre.objects.get_or_create(**genre_data) - instance.genres.add(genre) - + actors_data = validated_data.pop("actors", []) + genres_data = validated_data.pop("genres", []) + if actors_data: + instance.actors.set(actors_data) + if genres_data: + instance.genres.set(genres_data) instance.save() - return instance diff --git a/cinema/views.py b/cinema/views.py index d9dd1aca5..645841abf 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -1,9 +1,7 @@ from django.http import Http404 -from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status, mixins, generics, viewsets -from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from cinema.models import Movie, Genre, Actor, CinemaHall @@ -49,6 +47,14 @@ def put(self, request, pk): return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + def patch(self, request, pk): + genre = self.get_object(pk) + serializer = GenreSerializer(genre, data=request.data, partial=True) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + def delete(self, request, pk): genre = self.get_object(pk) genre.delete() @@ -83,6 +89,9 @@ def get(self, request, *args, **kwargs): def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) + def patch(self, request, *args, **kwargs): + return self.partial_update(request, *args, **kwargs) + def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) From 1486269d268d2a9e544da5629dc9541384eb54ba Mon Sep 17 00:00:00 2001 From: Denis Komandyr Date: Thu, 30 Nov 2023 02:57:10 +0200 Subject: [PATCH 3/5] Fix requirements for serializers --- cinema/serializers.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cinema/serializers.py b/cinema/serializers.py index d6cd98bc2..066c5c1f1 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -5,7 +5,7 @@ class GenreSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - name = serializers.CharField(max_length=255) + name = serializers.CharField(max_length=255, required=True) def create(self, validated_data): return Genre.objects.create(**validated_data) @@ -18,8 +18,8 @@ def update(self, instance, validated_data): class ActorSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - first_name = serializers.CharField(max_length=255) - last_name = serializers.CharField(max_length=255) + first_name = serializers.CharField(max_length=255, required=True) + last_name = serializers.CharField(max_length=255, required=True) def create(self, validated_data): return Actor.objects.create(**validated_data) @@ -37,9 +37,9 @@ def update(self, instance, validated_data): class CinemaHallSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - name = serializers.CharField(max_length=255) - rows = serializers.IntegerField() - seats_in_row = serializers.IntegerField() + name = serializers.CharField(max_length=255, required=True) + rows = serializers.IntegerField(required=True) + seats_in_row = serializers.IntegerField(required=True) def create(self, validated_data): return CinemaHall.objects.create(**validated_data) @@ -56,11 +56,11 @@ def update(self, instance, validated_data): class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - title = serializers.CharField(max_length=255) - description = serializers.CharField() + title = serializers.CharField(max_length=255, required=True) + description = serializers.CharField(required=False) actors = ActorSerializer(many=True, required=False) genres = GenreSerializer(many=True, required=False) - duration = serializers.IntegerField() + duration = serializers.IntegerField(required=True) def create(self, validated_data): actors_data = validated_data.pop("actors", []) From 0efd1190ceb191f84cb995f45d63b538ffc8f67f Mon Sep 17 00:00:00 2001 From: Denis Komandyr Date: Mon, 12 Feb 2024 01:30:09 +0200 Subject: [PATCH 4/5] Provide status to GenreDetail method get. Delete useless required=True in serializers.py --- cinema/serializers.py | 16 ++++++++-------- cinema/views.py | 7 ++----- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/cinema/serializers.py b/cinema/serializers.py index 066c5c1f1..0e0616619 100644 --- a/cinema/serializers.py +++ b/cinema/serializers.py @@ -5,7 +5,7 @@ class GenreSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - name = serializers.CharField(max_length=255, required=True) + name = serializers.CharField(max_length=255) def create(self, validated_data): return Genre.objects.create(**validated_data) @@ -18,8 +18,8 @@ def update(self, instance, validated_data): class ActorSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - first_name = serializers.CharField(max_length=255, required=True) - last_name = serializers.CharField(max_length=255, required=True) + first_name = serializers.CharField(max_length=255) + last_name = serializers.CharField(max_length=255) def create(self, validated_data): return Actor.objects.create(**validated_data) @@ -37,9 +37,9 @@ def update(self, instance, validated_data): class CinemaHallSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - name = serializers.CharField(max_length=255, required=True) - rows = serializers.IntegerField(required=True) - seats_in_row = serializers.IntegerField(required=True) + name = serializers.CharField(max_length=255) + rows = serializers.IntegerField() + seats_in_row = serializers.IntegerField() def create(self, validated_data): return CinemaHall.objects.create(**validated_data) @@ -56,11 +56,11 @@ def update(self, instance, validated_data): class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) - title = serializers.CharField(max_length=255, required=True) + title = serializers.CharField(max_length=255) description = serializers.CharField(required=False) actors = ActorSerializer(many=True, required=False) genres = GenreSerializer(many=True, required=False) - duration = serializers.IntegerField(required=True) + duration = serializers.IntegerField() def create(self, validated_data): actors_data = validated_data.pop("actors", []) diff --git a/cinema/views.py b/cinema/views.py index 645841abf..7bcd3b0ce 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -29,15 +29,12 @@ def post(self, request): class GenreDetail(APIView): def get_object(self, pk): - try: - return Genre.objects.get(pk=pk) - except Genre.DoesNotExist: - raise Http404 + return get_object_or_404(Genre, pk=pk) def get(self, request, pk): genre = self.get_object(pk) serializer = GenreSerializer(genre) - return Response(serializer.data) + return Response(serializer.data, status=status.HTTP_200_OK) def put(self, request, pk): genre = self.get_object(pk) From dcea38ea547ddb9ae9ae67fc47ee13c92c17675f Mon Sep 17 00:00:00 2001 From: Denis Komandyr Date: Mon, 12 Feb 2024 01:33:23 +0200 Subject: [PATCH 5/5] Forgotten import --- cinema/views.py | 1 + 1 file changed, 1 insertion(+) diff --git a/cinema/views.py b/cinema/views.py index 7bcd3b0ce..b7228b9d5 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -1,4 +1,5 @@ from django.http import Http404 +from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import status, mixins, generics, viewsets