2

我想在我的網站中設置restful API。我使用了django-rest-framework。 當我從數據庫中獲取對象時,它不顯示相關對象。爲什麼django-rest-framework不顯示OneToOneField數據 - django

以下片段是我的第一個模型(父模型):

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) 

如您在第二個片段看, teacherProfile模型中獲得它的值。

但在django-rest-framework API視圖中,不是顯示teahcer的名稱,而是顯示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

嘗試,更detaile 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') 
+0

抱歉,嘗試刪除'many' –

+0

是的,通過去除許多=真它的工作。 – msln

+0

很高興爲您效勞) –