Skip to content

Commit

Permalink
update avg_rating
Browse files Browse the repository at this point in the history
  • Loading branch information
kenmoh committed Dec 2, 2023
1 parent 7d86d79 commit bb8c194
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
2 changes: 1 addition & 1 deletion app/schema/movie_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class MovieCreateSchema(BaseModel):
class MovieResponseSchema(MovieCreateSchema):
id: int
cover_image_url: str
average_rating: float | None
average_rating: float
reviews: list[ReviewResponseSchema]


Expand Down
14 changes: 13 additions & 1 deletion app/services/movie_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from app.database import session
from app.forms import AddMovieForm
from app.utils import delete_image
from app.services.reviews_service import get_all_reviews_by_movie

""" START MOVIE OPERATIONS """

Expand All @@ -14,7 +15,18 @@ def get_all_movies(db: session):
:param db:
:return: All movies in the database
"""
return db.query(Movie).all()
movies = db.query(Movie).all()
for movie in movies:
reviews = get_all_reviews_by_movie(movie.id, db)

if reviews:
average_rating = sum(review.rating for review in reviews) / len(reviews)
movie.average_rating = average_rating
else:
movie.average_rating = 0.0

return movies



def add_movie(movie: AddMovieForm, db: session):
Expand Down
9 changes: 2 additions & 7 deletions app/services/reviews_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,8 @@ def add_new_review(

def get_all_reviews_by_movie(movie_id, db: session):
try:
reviews = db.query(Review).filter(Review.movie_id == movie_id).all()
average_reviews = (
sum([review.review for review in reviews]) / len(reviews)
if len(reviews) > 0
else sum([review.review for review in reviews])
)
return {"reviews": reviews, "average_reviews": average_reviews}
return db.query(Review).filter(Review.movie_id == movie_id).all()

except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
Expand Down

0 comments on commit bb8c194

Please sign in to comment.