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 #724

Open
wants to merge 2 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
db.sqlite3
2 changes: 1 addition & 1 deletion cinema/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Generated by Django 4.0.4 on 2022-05-09 18:11

from django.db import migrations, models
import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):
Expand Down
8 changes: 5 additions & 3 deletions cinema/migrations/0002_initial.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Generated by Django 4.0.4 on 2022-05-09 18:11

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
Expand All @@ -19,14 +19,16 @@ class Migration(migrations.Migration):
model_name="order",
name="user",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
migrations.AddField(
model_name="moviesession",
name="cinema_hall",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="cinema.cinemahall"
on_delete=django.db.models.deletion.CASCADE,
to="cinema.cinemahall",
),
),
migrations.AddField(
Expand Down
6 changes: 3 additions & 3 deletions cinema/migrations/0003_movie_duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
class Migration(migrations.Migration):

dependencies = [
('cinema', '0002_initial'),
("cinema", "0002_initial"),
]

operations = [
migrations.AddField(
model_name='movie',
name='duration',
model_name="movie",
name="duration",
field=models.IntegerField(default=123),
preserve_default=False,
),
Expand Down
6 changes: 3 additions & 3 deletions cinema/migrations/0004_alter_genre_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
class Migration(migrations.Migration):

dependencies = [
('cinema', '0003_movie_duration'),
("cinema", "0003_movie_duration"),
]

operations = [
migrations.AlterField(
model_name='genre',
name='name',
model_name="genre",
name="name",
field=models.CharField(max_length=255, unique=True),
),
]
8 changes: 6 additions & 2 deletions cinema/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.conf import settings


class CinemaHall(models.Model):
Expand Down Expand Up @@ -39,7 +39,7 @@ class Movie(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
duration = models.IntegerField()
genres = models.ManyToManyField(Genre)
genres = models.ManyToManyField(Genre, related_name="movies")

Choose a reason for hiding this comment

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

Consider adding a related_name for the actors ManyToManyField in the Movie model for consistency and easier reverse querying, similar to the genres field.

actors = models.ManyToManyField(Actor)

class Meta:
Expand All @@ -60,6 +60,10 @@ class Meta:
def __str__(self):
return self.movie.title + " " + str(self.show_time)

@property
def available_spots(self) -> int:
return self.cinema_hall.capacity - self.tickets.count()


class Order(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
Expand Down
58 changes: 55 additions & 3 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from rest_framework import serializers

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


class GenreSerializer(serializers.ModelSerializer):
Expand All @@ -10,6 +11,8 @@ class Meta:


class ActorSerializer(serializers.ModelSerializer):
full_name = serializers.CharField(read_only=True)

class Meta:
model = Actor
fields = ("id", "first_name", "last_name", "full_name")
Expand Down Expand Up @@ -46,9 +49,25 @@ class Meta:


class MovieSessionSerializer(serializers.ModelSerializer):
movie_title = serializers.CharField(source="movie.title", read_only=True)
cinema_hall_name = serializers.CharField(
source="cinema_hall.name", read_only=True
)
cinema_hall_capacity = serializers.IntegerField(
source="cinema_hall.capacity", read_only=True
)

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


class MovieSessionListSerializer(MovieSessionSerializer):
Expand All @@ -59,6 +78,9 @@ class MovieSessionListSerializer(MovieSessionSerializer):
cinema_hall_capacity = serializers.IntegerField(
source="cinema_hall.capacity", read_only=True
)
tickets_available = serializers.IntegerField(
source="available_spots", read_only=True
)

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


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

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


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


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

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


class OrderSerializer(serializers.ModelSerializer):
tickets = TicketSerializer(many=True, read_only=True)

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


class OrderDetailSerializer(OrderSerializer):
tickets = TicketSerializer(many=True, read_only=True)
24 changes: 11 additions & 13 deletions cinema/urls.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
from django.urls import path, include
from django.urls import include, path
from rest_framework import routers

from cinema.views import (
GenreViewSet,
ActorViewSet,
CinemaHallViewSet,
MovieViewSet,
MovieSessionViewSet,
)
from cinema.views import (ActorViewSet, CinemaHallViewSet, GenreViewSet,
MovieSessionViewSet, MovieViewSet, OrderViewSet)

router = routers.DefaultRouter()
router.register("genres", GenreViewSet)
router.register("actors", ActorViewSet)
router.register("cinema_halls", CinemaHallViewSet)
router.register("movies", MovieViewSet)
router.register("movie_sessions", MovieSessionViewSet)
router.register("genres", GenreViewSet, basename="genres")
router.register("actors", ActorViewSet, basename="actors")
router.register("cinema_halls", CinemaHallViewSet, basename="cinema_halls")
router.register("movies", MovieViewSet, basename="movies")
router.register(
"movie_sessions", MovieSessionViewSet, basename="movie_sessions"
)
router.register("orders", OrderViewSet, basename="orders")

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

Expand Down
87 changes: 68 additions & 19 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination

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

from cinema.serializers import (
GenreSerializer,
ActorSerializer,
CinemaHallSerializer,
MovieSerializer,
MovieSessionSerializer,
MovieSessionListSerializer,
MovieDetailSerializer,
MovieSessionDetailSerializer,
MovieListSerializer,
)
from cinema.models import Actor, CinemaHall, Genre, Movie, MovieSession, Order
from cinema.serializers import (ActorSerializer, CinemaHallSerializer,
GenreSerializer, MovieDetailSerializer,
MovieListSerializer, MovieSerializer,
MovieSessionDetailSerializer,
MovieSessionListSerializer,
MovieSessionSerializer, OrderSerializer)


class GenreViewSet(viewsets.ModelViewSet):
queryset = Genre.objects.all()
queryset = Genre.objects.prefetch_related("movies")
serializer_class = GenreSerializer

@staticmethod
def params_to_ints(qs):
return [int(str_id) for str_id in qs.split(",")]

def get_queryset(self):
queryset = self.queryset
if genres := self.request.query_params.get("genres"):
genre_ids = self.params_to_ints(genres)
queryset = queryset.filter(id__in=genre_ids)
if actors := self.request.query_params.get("actors"):
actor_ids = self.params_to_ints(actors)
queryset = queryset.filter(movies__actors__id__in=actor_ids)
if title := self.request.query_params.get("title"):
queryset = queryset.filter(movies__title__icontains=title)
return queryset.distinct()


class ActorViewSet(viewsets.ModelViewSet):
queryset = Actor.objects.all()
Expand All @@ -31,28 +42,66 @@ class CinemaHallViewSet(viewsets.ModelViewSet):


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

def get_queryset(self):
queryset = self.queryset
if genres := self.request.query_params.get("genres"):
genre_ids = GenreViewSet.params_to_ints(genres)
queryset = queryset.filter(genres__id__in=genre_ids)
if actors := self.request.query_params.get("actors"):
actor_ids = GenreViewSet.params_to_ints(actors)
queryset = queryset.filter(actors__id__in=actor_ids)
if title := self.request.query_params.get("title"):
queryset = queryset.filter(title__icontains=title)
return queryset.distinct()

def get_serializer_class(self):
if self.action == "list":
return MovieListSerializer

if self.action == "retrieve":
return MovieDetailSerializer

return MovieSerializer


class MovieSessionViewSet(viewsets.ModelViewSet):
queryset = MovieSession.objects.all()
queryset = MovieSession.objects.select_related(
"movie", "cinema_hall"
).prefetch_related("tickets")
serializer_class = MovieSessionSerializer

def get_queryset(self):
queryset = self.queryset
if movie_id := self.request.query_params.get("movie"):
queryset = queryset.filter(movie__id=movie_id)
if date := self.request.query_params.get("date"):
queryset = queryset.filter(show_time__date=date)
return queryset.distinct()

def get_serializer_class(self):
if self.action == "list":
return MovieSessionListSerializer

if self.action == "retrieve":
return MovieSessionDetailSerializer

return MovieSessionSerializer


class OrderPagination(PageNumberPagination):
page_size = 10
page_size_query_param = "page_size"
max_page_size = 100


class OrderViewSet(viewsets.ModelViewSet):
serializer_class = OrderSerializer
pagination_class = OrderPagination

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

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