Serialize Objects with One-to-One Relationship Django

前端 未结 1 1845
抹茶落季
抹茶落季 2021-01-05 15:06

I am a newbie in django. I am working on a rest api. I have an optional \"is a\" relationship i.e Student is a Employee. I am trying to serialize these 2 models such that I

相关标签:
1条回答
  • 2021-01-05 15:30

    The Django REST framework has some nice tools for serializing nested objects.

    You need what they call a Nested Relationship. Like this -

    from rest_framework import serializers
    
    # define your models here ...
    
    class EmployeeSerializer(serializers.ModelSerializer):
      class Meta:
        model = Employee
        fields = ('full_name', 'email_id', 'mobile_no', 'is_job_ready', 'type', 'location_preference')
    
    class StudentSerializer(serializers.ModelSerializer):
      employee = EmployeeSerializer(read_only = True)
    
      class Meta:
        model = Student
        fields = ('college', 'year', 'is_with_college', 'employee')
    

    Then, you can load your serializer and use it something like this -

    from myapp.models import StudentSerializer
    
    student = Student.objects.first()
    serializer = StudentSerializer(student)
    
    serializer.data
    # { 'college': 'Naropa University',
    #    'is_with_college': True,
    #    'year': '2015'}
    #    'employee': {
    #      'full_name' : 'Chogyam Trungpa',
    #      'email_id' : 'teacher@naropa.edu',
    #      'mobile_no' : '555-555-5555',
    #      'is_job_ready' : True,
    #      'type' :'Teacher',
    #      'location_preference' : 'Boulder, CO'
    #    }
    #  }
    
    0 讨论(0)
提交回复
热议问题