Skip to content

Commit

Permalink
chore(backend): add is my quiz field to the serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
umitcan07 committed Nov 20, 2024
1 parent 67feee8 commit 01e7cd2
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions backend/core/serializers/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.contrib.auth import get_user_model
from faker import Faker
from rest_framework import serializers

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

0 comments on commit 01e7cd2

Please sign in to comment.