- 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’]
2 Réponses
+ 1
Hello, Learn!
You try the code here?
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()