代码之家  ›  专栏  ›  技术社区  ›  msln

为什么django rest框架不显示OneToOneField数据-django

  •  2
  • msln  · 技术社区  · 7 年前

    我想在我的网站上设置restful API。我使用了django rest框架。

    class Profile(models.Model):
        user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE)
        name = models.CharField(max_length=30)
        family = models.CharField(max_length=50)
    

    下面是我的第二个模型(子模型):

    class Klass(models.Model):
        title = models.CharField(max_length=50)
        description = models.CharField(max_length=500)
        teacher = models.ForeignKey(Profile,related_name='teacher', on_delete=models.CASCADE)
        university = models.CharField(max_length=50, blank=True, null=True)
    

    teacher Profile 模型

    pk .

    # serializer
    class KlassSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Klass
            fields = ('id', 'title', 'description', 'teacher')
    
    # view
    class KlassView(APIView):
    
        def get(self, request, pk=None):
            if pk is not None:
                klass = Klass.objects.filter(pk=pk).get()
                serializer = KlassSerializer(klass)
                return Response({'message': 'class get ', 'data': serializer.data,})
    

    结果如下:

    {
        "message": "class get ",
        "data": {
            "id": 13,
            "title": "ُThe First Class",
            "description": "Nothing for now!",
            "teacher": 2
        }
    }
    

    我怎样才能解决这个问题? 谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Brown Bear    7 年前

    试试看,更多细节 nested-relationships

    class TeacherSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Profile
            fields = ('name')
    
    class KlassSerializer(serializers.ModelSerializer):
        teacher = TeacherSerializer(read_only=True)
    
        class Meta:
            model = Klass
            fields = ('id', 'title', 'description', 'teacher')