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

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Generated by Django 4.0.2 on 2024-11-11 17:39

from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('db', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orders', to=settings.AUTH_USER_MODEL)),

Choose a reason for hiding this comment

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

Ensure that the AUTH_USER_MODEL setting in your Django settings is correctly configured to use this custom User model. This is crucial for the ForeignKey relationship defined here.

],
options={
'ordering': ['-created_at'],
},
),
migrations.AlterField(
model_name='movie',
name='actors',
field=models.ManyToManyField(related_name='movies', to='db.Actor'),
),
migrations.AlterField(
model_name='movie',
name='genres',
field=models.ManyToManyField(related_name='movies', to='db.Genre'),
),
migrations.AlterField(
model_name='movie',
name='title',
field=models.CharField(db_index=True, max_length=255),
),
migrations.AlterField(
model_name='moviesession',
name='cinema_hall',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movie_sessions', to='db.cinemahall'),
),
migrations.AlterField(
model_name='moviesession',
name='movie',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movie_sessions', to='db.movie'),
),
migrations.CreateModel(
name='Ticket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('row', models.IntegerField()),
('seat', models.IntegerField()),
('movie_session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='db.moviesession')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='db.order')),
],
),
migrations.AddConstraint(
model_name='ticket',
constraint=models.UniqueConstraint(fields=('row', 'seat', 'movie_session'), name='ticket_constraint'),

Choose a reason for hiding this comment

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

The unique constraint on the Ticket model ensures that each combination of row, seat, and movie_session is unique. This is a good practice to prevent duplicate tickets for the same seat in a session.

),
]
77 changes: 76 additions & 1 deletion db/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.conf import settings
from django.db import models
from django.db.models import UniqueConstraint


class Genre(models.Model):
Expand All @@ -17,7 +21,7 @@ def __str__(self) -> str:


class Movie(models.Model):
title = models.CharField(max_length=255)
title = models.CharField(max_length=255, db_index=True)
description = models.TextField()
actors = models.ManyToManyField(to=Actor, related_name="movies")
genres = models.ManyToManyField(to=Genre, related_name="movies")
Expand Down Expand Up @@ -50,3 +54,74 @@ class MovieSession(models.Model):

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


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

Choose a reason for hiding this comment

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

Ensure that the AUTH_USER_MODEL setting in your Django settings is correctly configured to use this custom User model. This is crucial for the ForeignKey relationship defined here.

on_delete=models.CASCADE,
related_name="orders"
)

class Meta:
ordering = ["-created_at"]

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


class Ticket(models.Model):
row = models.IntegerField()
seat = models.IntegerField()

movie_session = models.ForeignKey(
to=MovieSession,
on_delete=models.CASCADE,
related_name="tickets"
)
order = models.ForeignKey(
to=Order,
on_delete=models.CASCADE,
related_name="tickets"
)

class Meta:
constraints = [
UniqueConstraint(
fields=["row", "seat", "movie_session"],
name="ticket_constraint",
)
]

def clean(self) -> None:
cinema_hall = self.movie_session.cinema_hall
if self.row > cinema_hall.rows:
raise ValidationError(
{
"row": [
"row number must be in available range: "
f"(1, rows): (1, {cinema_hall.rows})"
]
}
)
if self.seat > cinema_hall.seats_in_row:
raise ValidationError(
{
"seat": [
"seat number must be in available range: "
f"(1, seats_in_row): (1, {cinema_hall.seats_in_row})"
]
}
)
Comment on lines +97 to +116

Choose a reason for hiding this comment

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

The clean method in the Ticket model is correctly implemented to validate that the row and seat numbers are within the valid range for the associated cinema_hall. This ensures data integrity and prevents invalid ticket entries.


def save(self, *args, **kwargs) -> None:
self.full_clean()

Choose a reason for hiding this comment

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

Calling self.full_clean() in the save method ensures that the clean method is executed before saving, which is a good practice to maintain data integrity.

super().save(*args, **kwargs)

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


class User(AbstractUser):
pass
10 changes: 9 additions & 1 deletion services/movie.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.db import transaction
from django.db.models import QuerySet

from db.models import Movie
Expand All @@ -6,9 +7,14 @@
def get_movies(
genres_ids: list[int] = None,
actors_ids: list[int] = None,
title: str = None
) -> QuerySet:

queryset = Movie.objects.all()

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

if genres_ids:
queryset = queryset.filter(genres__id__in=genres_ids)

Expand All @@ -22,12 +28,14 @@ def get_movie_by_id(movie_id: int) -> Movie:
return Movie.objects.get(id=movie_id)


@transaction.atomic
def create_movie(
movie_title: str,
movie_description: str,
genres_ids: list = None,
actors_ids: list = None,
) -> Movie:
) -> QuerySet:

Choose a reason for hiding this comment

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

The return type for create_movie is incorrectly specified as QuerySet. Since this function returns a single Movie instance, the return type should be Movie instead.


movie = Movie.objects.create(
title=movie_title,
description=movie_description,
Expand Down
10 changes: 9 additions & 1 deletion services/movie_session.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.db.models import QuerySet

from db.models import MovieSession
from db.models import MovieSession, Ticket


def create_movie_session(
Expand Down Expand Up @@ -42,3 +42,11 @@ def update_movie_session(

def delete_movie_session_by_id(session_id: int) -> None:
MovieSession.objects.get(id=session_id).delete()
Comment on lines 43 to 44

Choose a reason for hiding this comment

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

Implement exception handling to manage scenarios where the MovieSession with the given ID is not found. This will prevent potential runtime errors during deletion.



def get_taken_seats(movie_session_id: int) -> list[dict]:
return list(
Ticket.objects.filter(
movie_session_id=movie_session_id
).values("row", "seat")
)
46 changes: 46 additions & 0 deletions services/order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from datetime import datetime

from django.contrib.auth import get_user_model
from django.db import transaction

from db.models import Order, Ticket


@transaction.atomic()
def create_order(
tickets: list[dict],
username: str,
date: datetime = None) -> Order:

user = get_user_model().objects.get(username=username)

Choose a reason for hiding this comment

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

Consider handling exceptions when retrieving the user by username. If the user does not exist, get() will raise a DoesNotExist exception, which should be caught and handled appropriately.


order = Order.objects.create(user=user)

if date:
order.created_at = date
order.save()

Choose a reason for hiding this comment

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

The save() method is called twice in the create_order function: once after setting the created_at date and again implicitly when tickets are associated with the order. Consider refactoring to call save() only once after all modifications are complete to avoid redundancy.


for ticket_data in tickets:
movie_session = ticket_data.get("movie_session")
row = ticket_data.get("row")
seat = ticket_data.get("seat")

ticket = Ticket(
movie_session_id=movie_session,
order=order,
row=row,
seat=seat
)

ticket.full_clean()
ticket.save()

return order


def get_orders(username: str = None) -> Order:

Choose a reason for hiding this comment

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

The return type annotation for get_orders is incorrect. This function returns a QuerySet of Order objects, not a single Order. Consider updating the return type to QuerySet[Order].

if username:
user = get_user_model().objects.get(username=username)

Choose a reason for hiding this comment

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

Similar to the comment above, ensure that exceptions are handled when retrieving the user by username. This will prevent the application from crashing if the user is not found.


return Order.objects.filter(user=user)
return Order.objects.all()
56 changes: 56 additions & 0 deletions services/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from django.contrib.auth import get_user_model

from db.models import User


def create_user(
username: str,
password: str,
email: str = None,
first_name: str = None,
last_name: str = None) -> User:

user = get_user_model().objects.create_user(
username=username,
password=password
)

if email:
user.email = email
if first_name:
user.first_name = first_name
if last_name:
user.last_name = last_name

user.save()
return user


def get_user(user_id: int) -> User:
return get_user_model().objects.get(id=user_id)

Choose a reason for hiding this comment

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

Consider handling exceptions when retrieving the user by ID. If the user does not exist, get() will raise a DoesNotExist exception, which should be caught and handled appropriately.



def update_user(
user_id: int,
username: str = None,
password: str = None,
email: str = None,
first_name: str = None,
last_name: str = None
) -> User:

user = get_user_model().objects.get(id=user_id)

Choose a reason for hiding this comment

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

Similar to the comment above, ensure that exceptions are handled when retrieving the user by ID. This will prevent the application from crashing if the user is not found.


if username:
user.username = username
if password:
user.set_password(password)
if last_name:
user.last_name = last_name
if email:
user.email = email
if first_name:
user.first_name = first_name

user.save()
return user
4 changes: 4 additions & 0 deletions settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,9 @@
USE_TZ = False

Choose a reason for hiding this comment

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

Consider setting USE_TZ = True to enable timezone-aware datetimes, which is a recommended practice for handling time data in Django applications.


INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"db",
]

AUTH_USER_MODEL = "db.User"

Choose a reason for hiding this comment

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

The AUTH_USER_MODEL setting is correctly configured to use the custom User model from the db app. This ensures that the custom user model is used throughout the project.

Loading