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 1 commit
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),
),
]
106 changes: 40 additions & 66 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
@@ -1,19 +1,6 @@
from django.core.exceptions import ValidationError
from django.db import models
from django.conf import settings


class CinemaHall(models.Model):
name = models.CharField(max_length=255)
rows = models.IntegerField()
seats_in_row = models.IntegerField()

@property
def capacity(self) -> int:
return self.rows * self.seats_in_row

def __str__(self):
return self.name
from django.core.exceptions import ValidationError


class Genre(models.Model):
Expand All @@ -27,13 +14,26 @@ class Actor(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)

def __str__(self):
return self.first_name + " " + self.last_name

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

def __str__(self):
return self.full_name


class CinemaHall(models.Model):
name = models.CharField(max_length=255)
rows = models.IntegerField()
seats_in_row = models.IntegerField()

@property
def capacity(self):
return self.rows * self.seats_in_row

def __str__(self):
return self.name


class Movie(models.Model):
title = models.CharField(max_length=255)
Expand All @@ -42,9 +42,6 @@ class Movie(models.Model):
genres = models.ManyToManyField(Genre)
actors = models.ManyToManyField(Actor)

class Meta:
ordering = ["title"]

def __str__(self):
return self.title

Expand All @@ -54,70 +51,47 @@ class MovieSession(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
cinema_hall = models.ForeignKey(CinemaHall, on_delete=models.CASCADE)

class Meta:
ordering = ["-show_time"]

def __str__(self):
return self.movie.title + " " + str(self.show_time)
return f"{self.movie.title} - {self.show_time}"


class Order(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)

def __str__(self):
return str(self.created_at)

class Meta:
ordering = ["-created_at"]
return f"Order {self.id} - {self.created_at}"


class Ticket(models.Model):
movie_session = models.ForeignKey(
MovieSession, on_delete=models.CASCADE, related_name="tickets"
)
order = models.ForeignKey(
Order, on_delete=models.CASCADE, related_name="tickets"
)
order = models.ForeignKey(Order, on_delete=models.CASCADE,
related_name="tickets")
row = models.IntegerField()
seat = models.IntegerField()

class Meta:
unique_together = ("movie_session", "row", "seat")

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
if not (1 <= self.row <= self.movie_session.cinema_hall.rows):
raise ValidationError(
f"Row number must be between 1 and "
f"{self.movie_session.cinema_hall.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})"
}
)

def save(
self,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
if not (1 <= self.seat <= self.movie_session.cinema_hall.seats_in_row):
raise ValidationError(
f"Seat number must be between 1 and "
f"{self.movie_session.cinema_hall.seats_in_row}"
)

def save(self, *args, **kwargs):
self.full_clean()
super(Ticket, self).save(
force_insert, force_update, using, update_fields
)
super().save(*args, **kwargs)

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

class Meta:
unique_together = ("movie_session", "row", "seat")
return (f"Ticket for {self.movie_session} - "
f"Row {self.row}, Seat {self.seat}")
65 changes: 39 additions & 26 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from rest_framework import serializers

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 All @@ -10,6 +16,8 @@ class Meta:


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

class Meta:
model = Actor
fields = ("id", "first_name", "last_name", "full_name")
Expand All @@ -27,38 +35,26 @@ class Meta:
fields = ("id", "title", "description", "duration", "genres", "actors")


class MovieListSerializer(MovieSerializer):
genres = serializers.SlugRelatedField(
many=True, read_only=True, slug_field="name"
)
class MovieListSerializer(serializers.ModelSerializer):
genres = serializers.SlugRelatedField(many=True, read_only=True,
slug_field="name")
actors = serializers.SlugRelatedField(
many=True, read_only=True, slug_field="full_name"
)


class MovieDetailSerializer(MovieSerializer):
genres = GenreSerializer(many=True, read_only=True)
actors = ActorSerializer(many=True, read_only=True)

class Meta:
model = Movie
fields = ("id", "title", "description", "duration", "genres", "actors")


class MovieSessionSerializer(serializers.ModelSerializer):
class Meta:
model = MovieSession
fields = ("id", "show_time", "movie", "cinema_hall")


class MovieSessionListSerializer(MovieSessionSerializer):
class MovieSessionListSerializer(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_name = serializers.CharField(source="cinema_hall.name",
read_only=True)
cinema_hall_capacity = serializers.IntegerField(
source="cinema_hall.capacity", read_only=True
)
tickets_available = serializers.SerializerMethodField()

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

def get_tickets_available(self, obj):
return obj.cinema_hall.capacity - obj.tickets.count()

class MovieSessionDetailSerializer(MovieSessionSerializer):
movie = MovieListSerializer(many=False, read_only=True)
cinema_hall = CinemaHallSerializer(many=False, read_only=True)

class TicketSerializer(serializers.ModelSerializer):
class Meta:
model = MovieSession
fields = ("id", "show_time", "movie", "cinema_hall")
model = Ticket
fields = ("id", "row", "seat", "movie_session")


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

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

def create(self, validated_data):
tickets_data = validated_data.pop("tickets")
user = self.context["request"].user
order = Order.objects.create(user=user)
for ticket_data in tickets_data:
Ticket.objects.create(order=order, **ticket_data)
return order
4 changes: 1 addition & 3 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
Expand Up @@ -16,9 +16,7 @@ def test_get_actors(self):
response = self.client.get("/api/cinema/actors/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
actors_full_names = [actor["full_name"] for actor in response.data]
self.assertEqual(
sorted(actors_full_names), ["George Clooney", "Keanu Reeves"]
)
self.assertEqual(sorted(actors_full_names), ["George Clooney", "Keanu Reeves"])

def test_post_actors(self):
response = self.client.post(
Expand Down
12 changes: 3 additions & 9 deletions cinema/tests/test_cinema_hall_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def test_get_cinema_halls(self):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data[0]["name"], blue_hall["name"])
self.assertEqual(response.data[0]["rows"], blue_hall["rows"])
self.assertEqual(
response.data[0]["seats_in_row"], blue_hall["seats_in_row"]
)
self.assertEqual(response.data[0]["seats_in_row"], blue_hall["seats_in_row"])
vip_hall = {
"name": "VIP",
"rows": 6,
Expand All @@ -43,9 +41,7 @@ def test_get_cinema_halls(self):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data[1]["name"], vip_hall["name"])
self.assertEqual(response.data[1]["rows"], vip_hall["rows"])
self.assertEqual(
response.data[1]["seats_in_row"], vip_hall["seats_in_row"]
)
self.assertEqual(response.data[1]["seats_in_row"], vip_hall["seats_in_row"])

def test_post_cinema_halls(self):
response = self.client.post(
Expand All @@ -72,9 +68,7 @@ def test_get_cinema_hall(self):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data["name"], vip_hall["name"])
self.assertEqual(response.data["rows"], vip_hall["rows"])
self.assertEqual(
response.data["seats_in_row"], vip_hall["seats_in_row"]
)
self.assertEqual(response.data["seats_in_row"], vip_hall["seats_in_row"])
self.assertEqual(response.data["capacity"], vip_hall["capacity"])

def test_get_invalid_cinema_hall(self):
Expand Down
20 changes: 5 additions & 15 deletions cinema/tests/test_movie_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ def setUp(self):
self.comedy = Genre.objects.create(
name="Comedy",
)
self.actress = Actor.objects.create(
first_name="Kate", last_name="Winslet"
)
self.actress = Actor.objects.create(first_name="Kate", last_name="Winslet")
self.movie = Movie.objects.create(
title="Titanic",
description="Titanic description",
Expand All @@ -42,21 +40,15 @@ def test_get_movies(self):
self.assertEqual(movies.data[0][field], titanic[field])

def test_get_movies_with_genres_filtering(self):
movies = self.client.get(
f"/api/cinema/movies/?genres={self.comedy.id}"
)
movies = self.client.get(f"/api/cinema/movies/?genres={self.comedy.id}")
self.assertEqual(len(movies.data), 1)
movies = self.client.get(
f"/api/cinema/movies/?genres={self.comedy.id},2,3"
)
movies = self.client.get(f"/api/cinema/movies/?genres={self.comedy.id},2,3")
self.assertEqual(len(movies.data), 1)
movies = self.client.get("/api/cinema/movies/?genres=123213")
self.assertEqual(len(movies.data), 0)

def test_get_movies_with_actors_filtering(self):
movies = self.client.get(
f"/api/cinema/movies/?actors={self.actress.id}"
)
movies = self.client.get(f"/api/cinema/movies/?actors={self.actress.id}")
self.assertEqual(len(movies.data), 1)
movies = self.client.get(f"/api/cinema/movies/?actors={123}")
self.assertEqual(len(movies.data), 0)
Expand Down Expand Up @@ -111,9 +103,7 @@ def test_get_movie(self):
self.assertEqual(response.data["genres"][1]["name"], "Comedy")
self.assertEqual(response.data["actors"][0]["first_name"], "Kate")
self.assertEqual(response.data["actors"][0]["last_name"], "Winslet")
self.assertEqual(
response.data["actors"][0]["full_name"], "Kate Winslet"
)
self.assertEqual(response.data["actors"][0]["full_name"], "Kate Winslet")

def test_get_invalid_movie(self):
response = self.client.get("/api/cinema/movies/100/")
Expand Down
Loading
Loading