Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #730

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ venv/
.pytest_cache/
**__pycache__/
*.pyc
app/db.sqlite3
app/db.sqlite3
tests
27 changes: 20 additions & 7 deletions cinema/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,21 @@ class Ticket(models.Model):
row = models.IntegerField()
seat = models.IntegerField()

def clean(self):
@staticmethod
def validate_ticket(
row: int,
seat: int,
movie_session: int,
error_to_raise
) -> None:
cinema_hall = movie_session.cinema_hall
for ticket_attr_value, ticket_attr_name, cinema_hall_attr_name in [
(self.row, "row", "rows"),
(self.seat, "seat", "seats_in_row"),
(row, "row", "rows"),
(seat, "seat", "seats_in_row"),
]:
count_attrs = getattr(
self.movie_session.cinema_hall, cinema_hall_attr_name
)
count_attrs = getattr(cinema_hall, cinema_hall_attr_name)
if not (1 <= ticket_attr_value <= count_attrs):
raise ValidationError(
raise error_to_raise(
{
ticket_attr_name: f"{ticket_attr_name} "
f"number must be in available range: "
Expand All @@ -102,6 +107,14 @@ def clean(self):
}
)

def clean(self):
Ticket.validate_ticket(
row=self.row,
seat=self.seat,
movie_session=self.movie_session,
error_to_raise=ValidationError
)

def save(
self,
force_insert=False,
Expand Down
115 changes: 108 additions & 7 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from rest_framework.validators import UniqueTogetherValidator, ValidationError
from django.db import transaction
from rest_framework import serializers

from cinema.models import Genre, Actor, CinemaHall, Movie, MovieSession
from cinema.models import (
Genre,
Actor,
CinemaHall,
Movie,
MovieSession,
Order,
Ticket
)


class GenreSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -46,12 +56,13 @@ class Meta:


class MovieSessionSerializer(serializers.ModelSerializer):

class Meta:
model = MovieSession
fields = ("id", "show_time", "movie", "cinema_hall")
fields = ["id", "show_time", "movie", "cinema_hall"]


class MovieSessionListSerializer(MovieSessionSerializer):
class MovieSessionForOrderSerializer(serializers.ModelSerializer):
movie_title = serializers.CharField(source="movie.title", read_only=True)
cinema_hall_name = serializers.CharField(
source="cinema_hall.name", read_only=True
Expand All @@ -62,19 +73,109 @@ class MovieSessionListSerializer(MovieSessionSerializer):

class Meta:
model = MovieSession
fields = (
fields = [
"id",
"show_time",
"cinema_hall",
"movie_title",
"cinema_hall_name",
"cinema_hall_capacity",
)
"cinema_hall_capacity"
]


class MovieSessionListSerializer(MovieSessionForOrderSerializer):
tickets_available = serializers.IntegerField(read_only=True)

class Meta:
model = MovieSession
fields = MovieSessionForOrderSerializer.Meta.fields + [
"tickets_available",
]


class TicketSerializer(serializers.ModelSerializer):
movie_session = MovieSessionListSerializer(many=False, read_only=True)

class Meta:
model = Ticket
fields = ("id", "row", "seat", "movie_session")


class TicketForOrderSerializer(serializers.ModelSerializer):
movie_session = MovieSessionForOrderSerializer(many=False, read_only=True)

class Meta:
model = Ticket
fields = ("id", "row", "seat", "movie_session")


class TicketSeatsSerializer(TicketSerializer):

class Meta:
model = Ticket
fields = ("row", "seat")


class MovieSessionDetailSerializer(MovieSessionSerializer):
movie = MovieListSerializer(many=False, read_only=True)
cinema_hall = CinemaHallSerializer(many=False, read_only=True)
taken_places = TicketSeatsSerializer(
many=True,
read_only=True,
source="tickets",
)

class Meta:
model = MovieSession
fields = ("id", "show_time", "movie", "cinema_hall")
fields = ("id", "show_time", "movie", "cinema_hall", "taken_places")


class TicketCreateSerializer(serializers.ModelSerializer):

class Meta:
model = Ticket
fields = ("row", "seat", "movie_session")
validators = [
UniqueTogetherValidator(
queryset=Ticket.objects.all(),
fields=("row", "seat", "movie_session"),
),
]

def validate(self, attrs):
Ticket.validate_ticket(
row=attrs["row"],
seat=attrs["seat"],
movie_session=attrs["movie_session"],
error_to_raise=serializers.ValidationError
)
return attrs


class OrderGetSerializer(serializers.ModelSerializer):
tickets = TicketForOrderSerializer(many=True, read_only=True)

class Meta:
model = Order
fields = ("id", "tickets", "created_at")


class OrderCreateSerializer(serializers.ModelSerializer):
tickets = TicketCreateSerializer(
many=True,
read_only=False,
allow_empty=False
)

class Meta:
model = Order
fields = ("tickets",)

def create(self, validated_data):
with transaction.atomic():
tickets_data = validated_data.pop("tickets")
order = Order.objects.create(**validated_data)
for tickets_data in tickets_data:
ticket = Ticket.objects.create(order=order, **tickets_data)
order.tickets.add(ticket)
return order
3 changes: 2 additions & 1 deletion cinema/tests/test_movie_session_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def test_get_movie_sessions_filtered_by_movie(self):

def test_get_movie_sessions_filtered_by_movie_and_data(self):
movie_sessions = self.client.get(
f"/api/cinema/movie_sessions/?movie={self.movie.id}&date=2022-09-2"
f"/api/cinema/movie_sessions/?movie="
f"{self.movie.id}&date=2022-09-2"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The date format in the query string should be zero-padded for the day part. Change 2022-09-2 to 2022-09-02 to maintain consistency and avoid potential issues with date parsing.

)
self.assertEqual(movie_sessions.status_code, status.HTTP_200_OK)
self.assertEqual(len(movie_sessions.data), 1)
Expand Down
2 changes: 2 additions & 0 deletions cinema/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
CinemaHallViewSet,
MovieViewSet,
MovieSessionViewSet,
OrderViewSet,
)

router = routers.DefaultRouter()
Expand All @@ -15,6 +16,7 @@
router.register("cinema_halls", CinemaHallViewSet)
router.register("movies", MovieViewSet)
router.register("movie_sessions", MovieSessionViewSet)
router.register("orders", OrderViewSet)

urlpatterns = [path("", include(router.urls))]

Expand Down
106 changes: 99 additions & 7 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
from rest_framework import viewsets
from django.db.models import Count, F

from cinema.models import Genre, Actor, CinemaHall, Movie, MovieSession
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination

from cinema.models import (
Genre,
Actor,
CinemaHall,
Movie,
MovieSession,
Order,
Ticket
)

from cinema.serializers import (
GenreSerializer,
Expand All @@ -12,9 +23,17 @@
MovieDetailSerializer,
MovieSessionDetailSerializer,
MovieListSerializer,
OrderGetSerializer,
OrderCreateSerializer,
)


class MixinParamsToListInt:
@staticmethod
def params_to_list_int(query_string):
return [int(litera) for litera in query_string.split(",")]


class GenreViewSet(viewsets.ModelViewSet):
queryset = Genre.objects.all()
serializer_class = GenreSerializer
Expand All @@ -30,8 +49,8 @@ class CinemaHallViewSet(viewsets.ModelViewSet):
serializer_class = CinemaHallSerializer


class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
class MovieViewSet(MixinParamsToListInt, viewsets.ModelViewSet):
queryset = Movie.objects.all().prefetch_related("actors", "genres")
serializer_class = MovieSerializer

def get_serializer_class(self):
Expand All @@ -43,10 +62,34 @@ def get_serializer_class(self):

return MovieSerializer

def get_queryset(self):
queryset = self.queryset

actors = self.request.query_params.get("actors")
genres = self.request.query_params.get("genres")
title = self.request.query_params.get("title")

class MovieSessionViewSet(viewsets.ModelViewSet):
queryset = MovieSession.objects.all()
serializer_class = MovieSessionSerializer
if actors:
actors = self.params_to_list_int(actors)
queryset = queryset.filter(
actors__in=actors)
if genres:
genres = self.params_to_list_int(genres)
queryset = queryset.filter(genres__in=genres)
if title:
queryset = queryset.filter(title__icontains=title)

return queryset.distinct()


class MovieSessionViewSet(MixinParamsToListInt, viewsets.ModelViewSet):
queryset = MovieSession.objects.all().select_related(
"movie",
"cinema_hall"
).prefetch_related("tickets").annotate(
tickets_available=F("cinema_hall__rows") * F(
"cinema_hall__seats_in_row") - Count("tickets")
)

def get_serializer_class(self):
if self.action == "list":
Expand All @@ -56,3 +99,52 @@ def get_serializer_class(self):
return MovieSessionDetailSerializer

return MovieSessionSerializer

def get_queryset(self):
queryset = self.queryset

actors = self.request.query_params.get("actors")
genres = self.request.query_params.get("genres")
date = self.request.query_params.get("date")
movie = self.request.query_params.get("movie")

if actors:
actors = self.params_to_list_int(actors)
queryset = queryset.filter(movie__actors__in=actors)
if genres:
genres = self.params_to_list_int(genres)
queryset = queryset.filter(movie__genres__in=genres)
if date:
queryset = queryset.filter(show_time__date=date)
if movie:
movie = self.params_to_list_int(movie)
queryset = queryset.filter(movie__in=movie)

return queryset.distinct()


class OrderResultsSetPagination(PageNumberPagination):
page_size = 10
page_size_query_param = "page_size"
max_page_size = 20


class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all().select_related("user").prefetch_related(
"tickets__movie_session__cinema_hall",
"tickets__movie_session__movie"
)

pagination_class = OrderResultsSetPagination

def get_serializer_class(self):
if self.action == "list":
return OrderGetSerializer
elif self.action == "create":
return OrderCreateSerializer

def get_queryset(self):
return self.queryset.filter(user=self.request.user)

def perform_create(self, serializer):
serializer.save(user=self.request.user)
Loading
Loading