39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
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}"
|