How to combine two different models on the basis of user and send a single response- Django Rest Framework

Viewed 54

I have two different models in my project. The StudentDetail model has an one-to-one connection with the student-user and the EnrollmentList has a foreign key connection with the student user. I want to combine information from both the models for that specific student-user and send them as as a single response rather than sending different responses. Below are the models and their serializers

StudentDetail/models.py

class StudentDetail(models.Model):
     id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
     
     user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
     
     name = models.CharField(max_length=100, null=True, blank=True)

StudentDetailSerializer

class StudentDetailSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = StudentDetail
        fields = "__all__"
        

Enrollment/models.py

class EnrollmentList(models.Model):
    
    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    
    student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='student')

EnrollSerializer

class AllReqs(serializers.ModelSerializer):
     class Meta:
         model = EnrollmentList
         fields = ['id','student_name', 'student_parent_name', 'standard', 'applying_for_standard', "board", 'home_tuition', 'address']

Now suppose a request is made, I want to combine the information from the StudentDetail and EnrollmentList for that specific student user to get a serialized data which may look like below example and send this as a single response

{
"student_name": name, #from StudentDetail
"home_tuition": home_tuition #from EnrollmentList
}

Please suggest to me the correct way to do it

1 Answers

Define your serializer like that:

class AllReqs(serializers.ModelSerializer):

    student_name = serializers.CharField(source='student.user.name')

     class Meta:
         model = EnrollmentList
         fields = ['id','student_name', 'home_tuition']

additional StudentDetail serializer:

class StudentDetailSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='user.name')
    home_tuition = serializers.SerializerMethodField()
    class Meta:
        model = StudentDetail
        fields = ['id','student_name', 'home_tuition']
    
   def get_home_tuition(self, obj):
        for enrollment in obj.user.students.all():
            return enrollment.home_tuition

I kindly ask the questioner to refer to the Django-Rest-Framework documentation. https://www.django-rest-framework.org/

Related