From 01e7cd2a379ebea4a8fc22401abfb9d3f714d320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=9Cmit=20Can=20Evleksiz?= Date: Thu, 21 Nov 2024 00:28:04 +0300 Subject: [PATCH] chore(backend): add is my quiz field to the serializer --- backend/core/serializers/serializers.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/backend/core/serializers/serializers.py b/backend/core/serializers/serializers.py index 8426fdc5..804f6f89 100644 --- a/backend/core/serializers/serializers.py +++ b/backend/core/serializers/serializers.py @@ -1,4 +1,3 @@ -from django.contrib.auth import get_user_model from faker import Faker from rest_framework import serializers @@ -223,15 +222,18 @@ class QuizSerializer(serializers.ModelSerializer): rating = serializers.SerializerMethodField() is_taken = serializers.SerializerMethodField() num_taken = serializers.SerializerMethodField() + is_my_quiz = serializers.SerializerMethodField() class Meta: model = Quiz fields = ( 'id', 'title', 'description', 'difficulty', "author", - 'tags', 'type', 'created_at', 'questions', 'num_taken', "is_taken", "rating" + 'tags', 'type', 'created_at', 'questions', 'num_taken', "is_taken", "rating", + 'is_my_quiz' ) - read_only_fields = ("difficulty", 'created_at', 'num_taken', 'is_taken', 'rating', "author") + read_only_fields = ("difficulty", 'created_at', 'num_taken', 'is_taken', 'rating', "author", + 'is_my_quiz') def get_is_taken(self, obj): user = self.context['request'].user @@ -257,6 +259,12 @@ def get_rating(self, obj): # Round the average score to 1 decimal place return {"score": round(result['avg_score'], 1), "count": result['count']} + # TODO: Check whether this works on the client side. + def get_is_my_quiz(self, obj): + user = self.context['request'].user + if not user.is_authenticated: + return False + return obj.author == user def calculate_difficulty(self, questions): # implement this method to calculate the difficulty of a quiz via external api @@ -352,4 +360,4 @@ def validate(self, attrs): if ForumBookmark.objects.filter(user=user, forum_question=forum_question).exists(): raise serializers.ValidationError("You have already bookmarked this forum question.") - return attrs + return attrs \ No newline at end of file