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

Solution #734

Open
wants to merge 5 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ venv/
.pytest_cache/
**__pycache__/
*.pyc
app/db.sqlite3
db.sqlite3
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.1 on 2024-12-11 23:32

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("cinema", "0004_alter_genre_name"),
]

operations = [
migrations.AlterUniqueTogether(
name="ticket",
unique_together=set(),
),
migrations.AddConstraint(
model_name="ticket",
constraint=models.UniqueConstraint(
fields=("row", "seat", "movie_session"), name="unique_ticket"
),
),
]
62 changes: 42 additions & 20 deletions cinema/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.core.exceptions import ValidationError
from django.db import models
from django.conf import settings
from django.db.models import UniqueConstraint


class CinemaHall(models.Model):
Expand Down Expand Up @@ -31,7 +32,7 @@ def __str__(self):
return self.first_name + " " + self.last_name

@property
def full_name(self):
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"


Expand Down Expand Up @@ -84,23 +85,47 @@ class Ticket(models.Model):
row = models.IntegerField()
seat = models.IntegerField()

def clean(self):
for ticket_attr_value, ticket_attr_name, cinema_hall_attr_name in [
(self.row, "row", "rows"),
(self.seat, "seat", "seats_in_row"),
]:
count_attrs = getattr(
self.movie_session.cinema_hall, cinema_hall_attr_name
class Meta:
constraints = [
UniqueConstraint(fields=["row", "seat", "movie_session"],
name="unique_ticket")
]

@staticmethod
def validate_seat(
row: int,
seat: int,
num_rows: int,
num_seats: int,
error: callable):
if not (1 <= row <= num_rows):
raise error(
{
"row": [
f"row number must be in available range: (1, rows): "
f"(1, {num_rows})"
]
}
)
if not (1 <= ticket_attr_value <= count_attrs):
raise ValidationError(
{
ticket_attr_name: f"{ticket_attr_name} "
f"number must be in available range: "
f"(1, {cinema_hall_attr_name}): "
f"(1, {count_attrs})"
}
)
if not (1 <= seat <= num_seats):
raise error(
{
"seat": [
f"seat number must be in available range: "
f"(1, seats_in_row): "
f"(1, {num_seats})"
]
}
)

def clean(self):
self.validate_seat(
self.row,
self.seat,
self.movie_session.cinema_hall.rows,
self.movie_session.cinema_hall.seats_in_row,
ValidationError
)

def save(
self,
Expand All @@ -118,6 +143,3 @@ def __str__(self):
return (
f"{str(self.movie_session)} (row: {self.row}, seat: {self.seat})"
)

class Meta:
unique_together = ("movie_session", "row", "seat")
79 changes: 77 additions & 2 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from django.db import transaction
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

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


class GenreSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -59,6 +69,7 @@ class MovieSessionListSerializer(MovieSessionSerializer):
cinema_hall_capacity = serializers.IntegerField(
source="cinema_hall.capacity", read_only=True
)
tickets_available = serializers.IntegerField(read_only=True)

class Meta:
model = MovieSession
Expand All @@ -68,13 +79,77 @@ class Meta:
"movie_title",
"cinema_hall_name",
"cinema_hall_capacity",
"tickets_available",
)


class TicketInfoSeatsSerializer(serializers.ModelSerializer):
class Meta:
model = Ticket
fields = ("row", "seat")
read_only_fields = fields

Choose a reason for hiding this comment

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

The read_only_fields attribute is redundant here because all fields in TicketInfoSeatsSerializer are already marked as read-only by default. You can remove this line to clean up the code.



class MovieSessionDetailSerializer(MovieSessionSerializer):
movie = MovieListSerializer(many=False, read_only=True)
cinema_hall = CinemaHallSerializer(many=False, read_only=True)
taken_places = TicketInfoSeatsSerializer(
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 TicketSerializer(serializers.ModelSerializer):

# movie_session = MovieSessionListSerializer(read_only=True)

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

def validate(self, attrs):
data = super(TicketSerializer, self).validate(attrs)
Ticket.validate_seat(
attrs["row"],
attrs["seat"],
attrs["movie_session"].cinema_hall.rows,
attrs["movie_session"].cinema_hall.seats_in_row,
serializers.ValidationError
)
return data


class OrderSerializer(serializers.ModelSerializer):

tickets = TicketSerializer(many=True, read_only=False, allow_empty=False)

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

def create(self, validated_data):
with transaction.atomic():
tickets_data = validated_data.pop("tickets")
order = Order.objects.create(**validated_data)
for ticket_data in tickets_data:
Ticket.objects.create(order=order, **ticket_data)
return order


class TicketsListSerializer(TicketSerializer):
movie_session = MovieSessionListSerializer(read_only=True)


class OrderListSerializer(OrderSerializer):
tickets = TicketsListSerializer(read_only=True, many=True)
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
92 changes: 91 additions & 1 deletion cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.core.serializers import serialize
from django.db.models import F, Count
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination

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

from cinema.serializers import (
GenreSerializer,
Expand All @@ -12,6 +15,8 @@
MovieDetailSerializer,
MovieSessionDetailSerializer,
MovieListSerializer,
OrderSerializer,
OrderListSerializer,
)


Expand All @@ -34,6 +39,28 @@ class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
serializer_class = MovieSerializer

def get_queryset(self):
queryset = super().get_queryset()
if self.action in ("list", "retrieve"):
queryset = self.queryset.prefetch_related("actors", "genres")

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

if actors:
actors_ids = [int(str_id) for str_id in actors.split(",")]
queryset = queryset.filter(actors__id__in=actors_ids)

if genres:
genres_ids = [int(str_id) for str_id in genres.split(",")]
queryset = queryset.filter(genres__id__in=genres_ids)

if title:
queryset = queryset.filter(title__icontains=title)

return queryset.distinct()

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

return MovieSessionSerializer

def get_queryset(self):
queryset = self.queryset

if self.action == "retrieve":
queryset = queryset.select_related("movie")

elif self.action == "list":
queryset = (
queryset.select_related("cinema_hall").annotate(
tickets_available=(
F("cinema_hall__rows") * F("cinema_hall__seats_in_row")
- Count("tickets")
)
)
).order_by("id")

movie = self.request.query_params.get("movie")
date = self.request.query_params.get("date")
if date:
queryset = queryset.filter(show_time__date=date)
if movie:
queryset = queryset.filter(movie__id=movie)
if self.action in ("list", "retrieve"):
queryset = queryset.select_related("movie", "cinema_hall")
Comment on lines +109 to +110

Choose a reason for hiding this comment

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

The select_related call for 'movie' and 'cinema_hall' is already handled in the 'retrieve' action. You can remove this redundant call within the 'list' and 'retrieve' check to avoid unnecessary repetition.


return queryset.distinct()


class OrderSetPagination(PageNumberPagination):
page_size = 1
page_size_query_param = "page_size"
max_page_size = 20


class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderSerializer
pagination_class = OrderSetPagination

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

if self.action == "list":
queryset = queryset.prefetch_related(
"tickets__movie_session__cinema_hall",
"tickets__movie_session__movie"
)
elif self.action == "retrieve":
queryset = queryset.prefetch_related("tickets__movie_session")

return queryset

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

def get_serializer_class(self):
serializer = self.serializer_class

if self.action == "list":
serializer = OrderListSerializer

return serializer
Loading