2

EDIT: I needed a student_count field in course because I'm supposed to use this model for REST API. If you can tell me how to add fields in serializer without adding to model, I'd take that too.

This is my model:

class Course(models.Model):
    student_count = models.PositiveIntegerField(default=0)
    students = models.ManyToManyField()

What I try to do is the following but it doesn't work.

Course.objects.update(student_count=F('students__count'))

The following works but it's not ideal

courses = Course.objects.all()
        for course in courses:
            course.student_count = course.students.count()
            course.save()
        return Course.objects.all()
Bill Vergara
  • 124
  • 2
  • 9
  • 2
    Are you sure you need to do this? You should probably calculate the count of students when you display the course, rather than storing it as a separate field on the model. – Daniel Roseman Mar 27 '18 at 10:09
  • just remove student_count from models and get student count from course.students.count() when you want count in code – Vaibhav Mar 27 '18 at 10:18
  • I needed a student_count field in course because I'm supposed to use this model for REST API. If you can tell me how to add fields in serializer without adding to model, I'd take that too. – Bill Vergara Mar 27 '18 at 10:37

1 Answers1

2

Try to add/update your serializer as below,

from django.db.models import Count

class CourseSerializer(serializers.ModelSerializer):
    count = serializers.SerializerMethodField(read_only=True)

    def get_count(self, model):
        return model.students.aggregate(count=Count('id'))['count']


    class Meta:
        model = Course
        fields = ('count',)



You can use aggregation Count() method instead of queryset.count() its more faster. Read this SO post, aggregate(Count()) vs queryset.count()

JPG
  • 82,442
  • 19
  • 127
  • 206