django rest-framework序列化器反向关系

时间:2018-02-14 09:34:33

标签: django django-rest-framework reverse relation serializer

我使用django rest-framework编写基于django的网站。 我想使用rest-framework来获取模型的数据。

这是我的model.py

class TimeTable(models.Model):
    subject_name = models.CharField(max_length=50)
    subject_code = models.CharField(max_length=10, unique=True)
    classification = models.CharField(max_length=50)
    professor = models.CharField(max_length=50)
    department = models.CharField(max_length=50)
    credit = models.CharField(max_length=1)
    year = models.CharField(max_length=4, default='2018')
    semester = models.CharField(max_length=1, default='1')

    def __str__(self):
        return self.subject_code + '-' + self.subject_name

class Class(models.Model):
    owner = models.ForeignKey(Profile, null=True)
    timetable = models.ForeignKey(TimeTable, null=True)
    grade = models.FloatField()

这是serializer.py

class TimeTableSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = TimeTable
        fields = ('url', 'subject_name', 'subject_code', 'classification', 'professor', 'department', 'credit', 'year', 'semester')

class ClassSerializer(serializers.HyperlinkedModelSerializer):
    timetables = TimeTableSerializer(read_only=True)
    class Meta:
        model = Class
        fields = ('url','owner', 'timetable', 'grade', 'timetables')

我想获得JSON响应 (http://localhost:8000/api/classes/

[
    {
        "url": "http://localhost:8000/api/classes/8/",
        "owner": "http://localhost:8000/api/profiles/19/",
        "timetable": "http://localhost:8000/api/timetables/3/",
        "grade": 4.5
        "timetables": {
                          "url": "http://localhost:8000/api/timetables/3/",
                          "subject_name": "Artificial Inteligence",
                          "subject_code": "3413513413",
                          "classification": "major",
                          "professor": "John Lee",
                          "department": "software",
                          "credit": "3",
                          "year": "2018",
                          "semester": "1"
                      }
    }
]

但我得到了这个

[
    {
        "url": "http://localhost:8000/api/classes/8/",
        "owner": "http://localhost:8000/api/profiles/19/",
        "timetable": "http://localhost:8000/api/timetables/3/",
        "grade": 4.5
    }
]

如何在JSON类中获取TimeTable的JSON数据?

1 个答案:

答案 0 :(得分:2)

class ClassSerializer(serializers.HyperlinkedModelSerializer):
    timetable = TimeTableSerializer(read_only=True)
    class Meta:
        model = Class
        fields = ('url','owner', 'timetable', 'grade')