인코스런 2기

Day3 - 장고 온보딩 프로젝트 3

B1001101 2022. 6. 9. 23:57

학습한 내용

Validation

 

Annotate Field

from rest_framework import generics
from django.db.models import Subquery, OuterRef, Avg, Count
from django.db.models.functions import Coalesce
from app.movie.models import Movie
from app.review.models import Review


class MovieListCreateView(generics.ListCreateAPIView):
    avg_rating_subquery = Review.objects.filter(movie=OuterRef('id')).values('movie').annotate(avg = Avg('rating')).values('avg')

    queryset = Movie.objects.annotate(
        avg_rating = Coalesce(Subquery(avg_rating_subquery), 0.0)
    )