# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-07 02:21
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import Avg
from ratings.models import Movie, Rating


def get_avg_movie_rating(apps, schema_editor):
    rating = apps.get_model("ratings", "Rating")
    movie = apps.get_model("ratings", "Movie")

    for movie in Movie.objects.values():
        movie_obj = Movie.objects.get(id=movie['id'])
        avg = Rating.objects.filter(movie_id=movie['id']).aggregate(Avg('rating'))
        movie_obj.avg_rating = (avg['rating__avg'])
        movie_obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ('ratings', '0005_movie_avg_rating'),
    ]

    operations = [
        migrations.RunPython(get_avg_movie_rating)
    ]
