Initial
This commit is contained in:
commit
e9b41dadab
30 files changed
+398
No files matched your search
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
from django.contrib import admin
|
||||
from .models import Movie, Rating
|
||||
|
||||
admin.site.register(Movie)
|
||||
admin.site.register(Rating)
|
||||
@@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ApiConfig(AppConfig):
|
||||
name = 'api'
|
||||
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 3.0.6 on 2020-05-28 10:13
|
||||
|
||||
from django.conf import settings
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Movie',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=32)),
|
||||
('description', models.TextField(max_length=360)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Rating',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('stars', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)])),
|
||||
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Movie')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'unique_together': {('user', 'movie')},
|
||||
'index_together': {('user', 'movie')},
|
||||
},
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,38 @@
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
|
||||
|
||||
class Movie(models.Model):
|
||||
title = models.CharField(max_length=32)
|
||||
description = models.TextField(max_length=360)
|
||||
|
||||
def no_of_ratings(self):
|
||||
ratings = Rating.objects.filter(movie=self)
|
||||
return len(ratings)
|
||||
|
||||
def average_ratings(self):
|
||||
ratings = Rating.objects.filter(movie=self)
|
||||
average = 0
|
||||
for rating in ratings:
|
||||
average += rating.stars
|
||||
if len(ratings) > 0:
|
||||
return average / len(ratings)
|
||||
return 0
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
|
||||
class Rating(models.Model):
|
||||
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
stars = models.IntegerField(
|
||||
validators=[MinValueValidator(1), MaxValueValidator(5)])
|
||||
|
||||
class Meta:
|
||||
unique_together = (('user'), 'movie')
|
||||
index_together = (('user'), 'movie')
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.movie.title} - {self.stars}"
|
||||
@@ -0,0 +1,29 @@
|
||||
from rest_framework import serializers
|
||||
from .models import Movie, Rating
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ["id", "username", "password"]
|
||||
extra_kwargs = {'password': {'write_only': True, 'required': True}}
|
||||
|
||||
def create(self, validated_data):
|
||||
user = User.objects.create_user(**validated_data)
|
||||
Token.objects.create(user=user)
|
||||
return user
|
||||
|
||||
|
||||
class MovieSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Movie
|
||||
fields = ["id", "title", "description",
|
||||
"no_of_ratings", "average_ratings"]
|
||||
|
||||
|
||||
class RatingSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Rating
|
||||
fields = ["id", "stars", "user", "movie"]
|
||||
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
from django.contrib import admin
|
||||
from django.urls import path, include
|
||||
from rest_framework import routers
|
||||
from .views import MovieViewSet, RatingViewSet, UserViewSet
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
router.register('movies', MovieViewSet)
|
||||
router.register('ratings', RatingViewSet)
|
||||
router.register('users', UserViewSet)
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
from django.contrib.auth.models import User
|
||||
from django.shortcuts import render
|
||||
from rest_framework import status, viewsets
|
||||
from rest_framework.authentication import TokenAuthentication
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||
from rest_framework.response import Response
|
||||
|
||||
from .models import Movie, Rating
|
||||
from .serializers import MovieSerializer, RatingSerializer, UserSerializer
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
class MovieViewSet(viewsets.ModelViewSet):
|
||||
queryset = Movie.objects.all()
|
||||
serializer_class = MovieSerializer
|
||||
authentication_classes = (TokenAuthentication,)
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
@action(detail=True, methods=['POST'])
|
||||
def rate_movie(self, request, pk=None):
|
||||
if 'stars' in request.data:
|
||||
|
||||
movie = Movie.objects.get(id=pk)
|
||||
stars = request.data['stars']
|
||||
user = request.user
|
||||
|
||||
try:
|
||||
rating = Rating.objects.get(user=user.id, movie=movie.id)
|
||||
rating.stars = stars
|
||||
rating.save()
|
||||
serializer = RatingSerializer(rating, many=False)
|
||||
response = {'message': f"Rating Updated",
|
||||
"result": serializer.data}
|
||||
return Response(response, status=status.HTTP_200_OK)
|
||||
except:
|
||||
rating = Rating.objects.create(
|
||||
user=user, movie=movie, stars=stars)
|
||||
serializer = RatingSerializer(rating, many=False)
|
||||
response = {'message': f"Rating Created",
|
||||
"result": serializer.data}
|
||||
return Response(response, status=status.HTTP_200_OK)
|
||||
|
||||
else:
|
||||
response = {'message': "stars field required"}
|
||||
return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class RatingViewSet(viewsets.ModelViewSet):
|
||||
queryset = Rating.objects.all()
|
||||
serializer_class = RatingSerializer
|
||||
authentication_classes = (TokenAuthentication,)
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
response = {'message': "Can't update rating like that"}
|
||||
return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
response = {'message': "Can't update rating like that"}
|
||||
return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
||||
Reference in new issue
Block a user