1

I have two tables

class student(models.Model):
    frist_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)


class subject(models.Model):
    student = models.ForeignKey(student)
    sub_name = models.CharField()

I want student list and subject count in serializer

my serializer

classs SubjectSerializers(serializers.ModelSerializer):
    class Meta:
        model = JobPosting
        fields = ('id','sub_name')

class StudentSerializers(serializers.ModelSerializer):
    sub = SubjectSerializers(source = 'student')
    class Meta:
        model = JobPosting
        fields = ('id','first_name', 'last_name','sub')

How can i get subject count for every student in serializer, Now i am geting subject table data but i want count like this

"detail": [{
        "id": 680,
        "first_name": "riya",
        "last_name": "tri",
        "subject_count": 5
      }],

1 Answer 1

3

You can achieve this by using a serializer method field

Then StudentSerializer becomes the following:

class StudentSerializers(serializers.ModelSerializer):
    sub = SubjectSerializers(source = 'student')
    subject_count = serializers.SerializerMethodField()

    class Meta:
        model = JobPosting
        fields = ('id','first_name', 'last_name','sub')

    def get_subject_count(self, student):
        return Subject.objects.filter(student=student).count()
Sign up to request clarification or add additional context in comments.

1 Comment

What would the performance implications of this be? Wouldn't this perform a separate query for each JobPosting object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.