- 1

Count number of students in a school in django, I get no result. Can someone help me ?

from django.db.models import Count class SchoolSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = School fields = ['name'] class StudentSerializer(serializers.HyperlinkedModelSerializer): school = SchoolSerializer() school.objects.annotate(num_of_students=Count('student')) class Meta: model = Student fields = ['first_name', 'last_name', 'school’]

2nd Nov 2021, 4:05 PM
Learn Languages
Learn Languages - avatar
2 ответов
+ 1
Hello, Learn! You try the code here?
26th Nov 2021, 8:49 PM
CGO!
CGO! - avatar
0
You could use a field in your schoolserializer like count = serializers.SerializerMethodField() And a method get_count(self, obj): return Student.objects.filter(school=obj).count()
5th Apr 2022, 4:50 PM
Fu Foy
Fu Foy - avatar