11.[drf] 별점 기능

별점

  • 리뷰 사이트에서 자주 쓰이는 별점 기능을 만들어보겠습니다.

models.py

from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import gettext_lazy as _
from common.models import TimeStampedUUIDModel

User = get_user_model()

class Rating(TimeStampedUUIDModel):
    class Range(models.IntegerChoices):
        RATING_1 = 1,_("poor")
        RATING_1 = 1,_("fair")
        RATING_1 = 1,_("good")
        RATING_1 = 1,_("very good")
        RATING_1 = 1,_("excellent")

    article = models.ForeignKey("articles.Article", related_name="article_ratings", on_delete=models.CASCADE)
    rated_by = models.ForeignKey(User, related_name = "user_who_rated", on_delete=models.CASCADE)

serializers.py

from rest_framework import serializers
from .models import Rating

class RatingSerializer(serializers.ModelSerializer):
    rated_by = serializers.SerializerMethodField(read_only=True)
    article = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Rating
        fields = ["id", "article", "rated_by", "value"]

    def get_rated_by(self, obj):
        return obj.rated_by.username

    def get_article(self, obj):
        return obj.article.title