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

implementation of serializer for Movie model and creation api views for endpoints #802

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
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions .idea/py-movie-api.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file added cinema/__init__.py
Empty file.
Binary file added cinema/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/admin.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/apps.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/models.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/serializers.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file added cinema/__pycache__/views.cpython-312.pyc
Binary file not shown.
5 changes: 5 additions & 0 deletions cinema/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import Movie

# Register your models here.
admin.site.register(Movie)
6 changes: 6 additions & 0 deletions cinema/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class CinemaAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'cinema'
26 changes: 26 additions & 0 deletions cinema/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 5.1.4 on 2025-01-09 18:47

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Movie',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('description', models.TextField(max_length=255)),
('duration', models.DurationField()),
],
options={
'verbose_name_plural': 'Movies',
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 5.1.4 on 2025-01-09 19:44

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('cinema', '0001_initial'),
]

operations = [
migrations.AlterModelOptions(
name='movie',
options={},
),
migrations.AlterField(
model_name='movie',
name='description',
field=models.TextField(),
),
migrations.AlterField(
model_name='movie',
name='duration',
field=models.IntegerField(),
Comment on lines +24 to +25

Choose a reason for hiding this comment

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

The duration field has been changed to an IntegerField. Ensure that this change is consistent with the Movie model and MovieSerializer to avoid any data handling issues.

),
]
18 changes: 18 additions & 0 deletions cinema/migrations/0003_alter_movie_duration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.1.4 on 2025-01-09 19:59

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('cinema', '0002_alter_movie_options_alter_movie_description_and_more'),
]

operations = [
migrations.AlterField(
model_name='movie',
name='duration',
field=models.DurationField(),
Comment on lines +15 to +16

Choose a reason for hiding this comment

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

The duration field is changed back to a DurationField. Ensure that this change is consistent with the Movie model and MovieSerializer to avoid any data handling issues.

),
]
Empty file added cinema/migrations/__init__.py
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
10 changes: 10 additions & 0 deletions cinema/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.db import models

# Create your models here.
class Movie(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
duration = models.DurationField()

Choose a reason for hiding this comment

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

The duration field is defined as DurationField here, but in the migration 0002_alter_movie_options_alter_movie_description_and_more.py, it is altered to IntegerField. Ensure that the field type in the model matches the latest migration to avoid inconsistencies.


def __str__(self):
return self.title
18 changes: 18 additions & 0 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from rest_framework import serializers
from cinema.models import Movie


class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=True, max_length=100)
description = serializers.CharField(required=False, max_length=255)
duration = serializers.DurationField()

Choose a reason for hiding this comment

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

The duration field is defined as DurationField in the serializer, but in the migration 0002_alter_movie_options_alter_movie_description_and_more.py, it is altered to IntegerField. Ensure that the field type in the serializer matches the latest migration to avoid inconsistencies.


def create(self, validated_data):
return Movie.objects.create(**validated_data)

def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.description = validated_data.get('description', instance.description)
instance.duration = validated_data.get('duration', instance.duration)
return instance
3 changes: 3 additions & 0 deletions cinema/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
9 changes: 9 additions & 0 deletions cinema/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.urls import path
from cinema.views import movies_list, movie_detail

app_name = 'cinema'

urlpatterns = [
path('cinema/movies/', movies_list, name='movies-list'),
path('cinema/movies/<int:movie_id>', movie_detail, name='movies-detail'),

Choose a reason for hiding this comment

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

It's a good practice to include a trailing slash at the end of the URL pattern for movie_detail to maintain consistency and avoid potential issues with URL resolution. Consider changing the pattern to 'cinema/movies/<int:movie_id>/'.

Choose a reason for hiding this comment

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

The URL pattern for movie_detail should end with a trailing slash to comply with the requirement that all endpoints end with a /. Update the path to 'cinema/movies/<int:movie_id>/'.

]
41 changes: 41 additions & 0 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from cinema.models import Movie
from cinema.serializers import MovieSerializer


# Create your views here.
@api_view(['GET', 'POST'])
def movies_list(request: HttpRequest) -> HttpResponse:
if request.method == "GET":
movies = Movie.objects.all()
serializer = MovieSerializer(movies, many=True)
return Response(
serializer.data,
status=status.HTTP_200_OK
)
elif request.method == "POST":
serializer = MovieSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)


@api_view(['GET', 'PUT', 'DELETE'])
def movie_detail(request: HttpRequest, movie_id: int) -> HttpResponse:
movie = get_object_or_404(Movie, pk=movie_id)
if request.method == "GET":
serializer = MovieSerializer(movie)
return Response(serializer.data, status=status.HTTP_200_OK)
elif request.method == "PUT":
serializer = MovieSerializer(movie, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:

Choose a reason for hiding this comment

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

In the movie_detail view, it's better to explicitly check for the 'DELETE' method instead of using else. This makes the code more readable and less error-prone if additional methods are added in the future. Consider changing else: to elif request.method == 'DELETE':.

movie.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Comment on lines +39 to +41

Choose a reason for hiding this comment

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

For better code readability and to reduce potential errors, explicitly check for the 'DELETE' method instead of using else. This makes the code more understandable and maintainable.

Binary file added db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movieapi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file added movieapi/__init__.py
Empty file.
Binary file added movieapi/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added movieapi/__pycache__/settings.cpython-312.pyc
Binary file not shown.
Binary file added movieapi/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file added movieapi/__pycache__/wsgi.cpython-312.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions movieapi/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for movieapi project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movieapi.settings')

application = get_asgi_application()
Loading