使用Django rest框架使用外键序列化子对象

时间:2016-12-30 08:13:47

标签: django rest django-rest-framework

使用django rest framework进行序列化

models.py

from django.db import models

class University( models.Model ):
    name = models.CharField( max_length = 50 )
    createdTime = models.DateTimeField( auto_now_add=True )
    updatedTime = models.DateTimeField( auto_now_add=True )

    class Meta:
       verbose_name = "University"
       verbose_name_plural = "Universities"

    def __unicode__( self ):
        return self.name

class Student( models.Model ):
    first_name = models.CharField( max_length = 50 )
    .......
    university = models.ForeignKey( University )
    .......

    @property
    def get_lookupName( self ):
        return self.first_name + self.last_name

    class Meta:
        verbose_name = "Student"
        verbose_name_plural = "Students"

    def __unicode__( self ):
        return '%s %s' % ( self.first_name , self.last_name )

serializers.py

from rest_framework import serializers
from .models import University, Student

class UniversitySerializer( serializers.ModelSerializer ):
    class Meta:
        model = University
        fields = ( 'id' , 'name' )

class StudentSerializer( serializers.ModelSerializer ):
    class Meta:
        model = Student

当我上场/学生/ 1 我在json中得到这个表示

{
    "id": 1,
    "first_name": "Alok",
    "last_name": "Kumar",
    ..........
    "email_alt2": "something@invalid2.com",
    "university": 1
}

但我希望这种表现形式:

{
    "id": 1,
    "first_name": "YYYYYY",
    ........
    "email_alt2": "something@invalid2.com",
    "university": {
            "id": 1,
            "name": XXXXX"",
            "links":[
                {
                    "rel": "self",
                    "href": ".....api/universities/1"
                }
             ]
        }
  }

我是否需要为此编写自定义序列化程序?

2 个答案:

答案 0 :(得分:0)

尝试drf' hyperlinkedmodelserializer。您的序列化程序可能如下所示。

来自rest_framework导入序列化程序 来自.models进口大学,学生

class UniversitySerializer( serializers.ModelSerializer ):
    class Meta:
        model = University
        fields = ( 'id' , 'name' )

class StudentSerializer( serializers.HyperlinkedModelSerializer ):
    class Meta:
        model = Student

如果您想要更多示例,可以找到一个简单的here

答案 1 :(得分:0)

您的Unviersity序列化程序未包含在StudentSerializer中,因此您必须添加它。

class UniversitySerializer( serializers.ModelSerializer ):
    class Meta:
        model = University
        fields = ( 'id' , 'name' )

class StudentSerializer( serializers.ModelSerializer ):
    # you need to add this
    university  = UniversitySerializer(many=False,read_only=True)
    class Meta:
        model = Student