Add average rating for Song model.

This commit is contained in:
Josh Washburne 2018-04-09 12:10:26 -04:00
parent 30ea69ac93
commit c186d2e997
2 changed files with 20 additions and 2 deletions

View file

@ -32,14 +32,16 @@ class GameSerializer(ModelSerializer):
class BasicSongSerializer(ModelSerializer):
class Meta:
model = Song
fields = ('id', 'album', 'artists', 'game', 'title')
fields = ('id', 'album', 'artists', 'game', 'title', 'average_rating',
'is_requestable')
class FullSongSerializer(ModelSerializer):
class Meta:
model = Song
fields = ('id', 'album', 'artists', 'published_date', 'game',
'num_played', 'last_played', 'length', 'song_type', 'title')
'num_played', 'last_played', 'length', 'song_type', 'title',
'average_rating', 'is_requestable')
class BasicSongRetrieveSerializer(BasicSongSerializer):

View file

@ -1,4 +1,5 @@
from datetime import timedelta
from decimal import getcontext, Decimal, ROUND_UP
from django.apps import apps
from django.db import models
@ -9,6 +10,10 @@ from core.behaviors import Disableable, Publishable, Timestampable
from .managers import RadioManager, SongManager
# Set decimal precision
getcontext().prec = 16
class Album(Disableable, Publishable, Timestampable, models.Model):
"""
A model for a music album.
@ -174,6 +179,17 @@ class Song(Disableable, Publishable, Timestampable, models.Model):
return self.title
full_title = property(_full_title)
def _average_rating(self):
"""
Decimal number of the average rating of a song from 1 - 5.
"""
ratings = self.rating_set.all()
if ratings:
avg = Decimal(ratings.aggregate(avg=models.Avg('value'))['avg'])
return avg.quantize(Decimal('.01'), rounding=ROUND_UP)
return None
average_rating = property(_average_rating)
def get_time_until_requestable(self):
"""
Length of time before a song can be requested again.