How to get an attribute of a serializer class in DRF?
I have a serializer class CourseSerializer
. A course can have a number of groups, lessons and etc.. A code for a serializer:
class CourseSerializer(serializers.ModelSerializer):
lessons = MiniLessonSerializer(many=True, read_only=True)
lessons_count = serializers.SerializerMethodField(read_only=True)
students_count = serializers.SerializerMethodField(read_only=True)
groups_filled_percent = serializers.SerializerMethodField(read_only=True)
demand_course_percent = serializers.SerializerMethodField(read_only=True)
def get_lessons_count(self, obj) -> int:
return obj.lessons.count()
def get_students_count(self, obj) -> int:
amount = Subscription.objects.filter().count()
return amount
def get_groups_filled_percent(self, obj) -> int:
counts = [group.users.count() for group in obj.groups.all()]
return ((sum(counts) / len(counts)) / 30) * 100
def get_demand_course_percent(self, obj) -> int:
users = CustomUser.objects.all().count()
students = Subscription.objects.filter().count()
return (students / users) * 100
As you see, a serializer has calculated attributes like lessons_count
, students_count
ad etc..
The question is: how can I get one of these attributes in a serializer method, for example:
def get_demand_course_percent(self, obj) -> int:
users = CustomUser.objects.all().count()
return (self.students_count / users) * 100_
If I do like this explicitly, it gives an Attribute error that there's no such attribute in a serializer class
How about implementing the method as a call?
def get_demand_course_percent(self, obj) -> int:
users = CustomUser.objects.all().count()
return (self.get_students_count(obj=None) / users) * 100_