如何在Django Rest框架中获取外键对象以显示完整对象

时间:2019-05-15 06:13:42

标签: python django django-rest-framework

我有一个用django_rest_framework构建的Django后端。我目前有一个外键对象。当我发出API请求以获取对象时,它将显示外键ID和仅ID。我希望它显示整个对象,而不只是显示外键的ID。不确定如何执行此操作,因为它并未在文档中真正说明如何执行操作。

代码如下:

“查看”页面:

from users.models import Profile
from ..serializers import ProfileSerializer
from rest_framework import viewsets

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    lookup_field = 'user__username'
    serializer_class = ProfileSerializer

有一个指向用户的用户外键。

网址:

from users.api.views.profileViews import ProfileViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'', ProfileViewSet, base_name='profile')
urlpatterns = router.urls

序列化器:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )

外观如下:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 1,
        "user": 3,
        "bio": "software engineer",
        "profile_pic": "http://127.0.0.1:8000/api/user/profile/profile_pics/allsum-logo-1.png",
        "facebook": "http://www.facebook.com/",
        "twitter": "http://www.twitter.com/"
    }
]

2 个答案:

答案 0 :(得分:3)

您可以创建一个UserSerializer并在ProfileSerializer中像这样使用(用作nested serializer):

class UserSerializer(serializers.ModelSerializer):
     class Meta:
         model = User
         fields = (
            'username',
            'first_name',
            # and so on..
         )

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )

答案 1 :(得分:3)

在您的 Meta 类的序列化程序中使用depth=1

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )
        depth = 1