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

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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ venv/
.pytest_cache/
**__pycache__/
*.pyc
app/db.sqlite3
app/db.sqlite3
.sqlite
.db3
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),
),
]
14 changes: 7 additions & 7 deletions cinema/models.py
Copy link

Choose a reason for hiding this comment

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

don't need rewrite default models

Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,11 @@ def clean(self):
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})"
ticket_attr_name: (
f"{ticket_attr_name} "
f"number must be in available range: "
f"(1, {cinema_hall_attr_name}): (1, {count_attrs})"
)
}
)

Expand All @@ -115,9 +116,8 @@ def save(
)

def __str__(self):
return (
f"{str(self.movie_session)} (row: {self.row}, seat: {self.seat})"
)
return (f"{str(self.movie_session)} "
f"(row: {self.row}, seat: {self.seat})")

class Meta:
unique_together = ("movie_session", "row", "seat")
58 changes: 56 additions & 2 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
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 @@ -59,6 +67,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 +77,58 @@ class Meta:
"movie_title",
"cinema_hall_name",
"cinema_hall_capacity",
"tickets_available",
)


class TicketSeatRowSerializer(serializers.ModelSerializer):
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 = TicketSeatRowSerializer(
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(many=False, read_only=True)

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

def validate(self, data):
data = super(TicketSerializer).validate(data)
ticket = Ticket(
movie_session=data.get("movie_session"),
row=data.get("row"),
seat=data.get("seat"),
)
ticket.full_clean()
return data


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

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

def create(self, validated_data):
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
9 changes: 2 additions & 7 deletions cinema/tests/test_actor_api.py
Copy link

Choose a reason for hiding this comment

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

why are you refactor tests?

Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from django.test import TestCase

from rest_framework import status
from rest_framework.test import APIClient

Expand Down Expand Up @@ -59,15 +58,11 @@ def test_put_actor(self):
)

def test_delete_actor(self):
response = self.client.delete(
"/api/cinema/actors/1/",
)
response = self.client.delete("/api/cinema/actors/1/")
db_actors_id_1 = Actor.objects.filter(id=1)
self.assertEqual(db_actors_id_1.count(), 0)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

def test_delete_invalid_actor(self):
response = self.client.delete(
"/api/cinema/actors/1000/",
)
response = self.client.delete("/api/cinema/actors/1000/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
2 changes: 1 addition & 1 deletion cinema/tests/test_cinema_hall_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,4 @@ def test_delete_invalid_cinema_hall(self):
response = self.client.delete(
"/api/cinema/cinema_halls/1000/",
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
2 changes: 1 addition & 1 deletion cinema/tests/test_genre_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ def test_delete_invalid_genre(self):
response = self.client.delete(
"/api/cinema/genres/1000/",
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
2 changes: 1 addition & 1 deletion cinema/tests/test_movie_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,4 @@ def test_delete_invalid_movie(self):
response = self.client.delete(
"/api/cinema/movies/1000/",
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
9 changes: 2 additions & 7 deletions cinema/tests/test_movie_session_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,7 @@ def setUp(self):
self.movie_session = MovieSession.objects.create(
movie=self.movie,
cinema_hall=self.cinema_hall,
show_time=datetime.datetime(
year=2022,
month=9,
day=2,
hour=9
),
show_time=datetime.datetime(year=2022, month=9, day=2, hour=9),
)

def test_get_movie_sessions(self):
Expand Down Expand Up @@ -126,4 +121,4 @@ def test_get_movie_session(self):
self.assertEqual(response.data["cinema_hall"]["capacity"], 140)
self.assertEqual(response.data["cinema_hall"]["rows"], 10)
self.assertEqual(response.data["cinema_hall"]["seats_in_row"], 14)
self.assertEqual(response.data["cinema_hall"]["name"], "White")
self.assertEqual(response.data["cinema_hall"]["name"], "White")
2 changes: 1 addition & 1 deletion cinema/tests/test_order_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,4 @@ def test_movie_session_list_tickets_available(self):
self.assertEqual(
response.data[0]["tickets_available"],
self.cinema_hall.capacity - 1,
)
)
8 changes: 7 additions & 1 deletion cinema/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
CinemaHallViewSet,
MovieViewSet,
MovieSessionViewSet,
OrderViewSet,
TicketViewSet,
)

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

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

app_name = "cinema"
83 changes: 77 additions & 6 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from django.db.models import Count, F
from rest_framework import viewsets

from cinema.models import Genre, Actor, CinemaHall, Movie, MovieSession
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,6 +22,8 @@
MovieDetailSerializer,
MovieSessionDetailSerializer,
MovieListSerializer,
OrderSerializer,
TicketSerializer,
)


Expand All @@ -37,12 +49,32 @@ class MovieViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == "list":
return MovieListSerializer

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

return 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()


class MovieSessionViewSet(viewsets.ModelViewSet):
queryset = MovieSession.objects.all()
Expand All @@ -51,8 +83,47 @@ class MovieSessionViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == "list":
return MovieSessionListSerializer

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

return MovieSessionSerializer

def get_queryset(self):
queryset =\
super().get_queryset().select_related("movie", "cinema_hall")

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

movie_id = self.request.query_params.get("movie")
date = self.request.query_params.get("date")

if movie_id:
queryset = queryset.filter(movie__id=movie_id)

if date:
try:
queryset = queryset.filter(show_time__date=date)
except ValueError:
pass

return queryset.distinct()


class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer


class OrderPagination(PageNumberPagination):
page_size = 5


class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderSerializer
pagination_class = OrderPagination
9 changes: 4 additions & 5 deletions cinema_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (
SECRET_KEY =\
"django-insecure-6vubhk2$++agnctay_4pxy_8cq)mosmn(*-#2b^v4cgsh-^!i3"
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand Down Expand Up @@ -101,15 +100,15 @@
},
{
"NAME": "django.contrib.auth.password_validation."
"MinimumLengthValidator",
"MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation."
"CommonPasswordValidator",
"CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation."
"NumericPasswordValidator",
"NumericPasswordValidator",
},
]

Expand Down
Loading