如何在Django Rest Framework中使外键对象显示完整的对象

3

我有一个使用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/"
    }
]

你可以创建一个 UserSerializer 并将其作为 ProfileSerializer 上的字段使用。 - Akshar Raaj
2个回答

14

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

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

谢谢!花了很长时间尝试使用SlugRelatedField使其工作... - George K

3
您可以创建一个UserSerializer并像这样在ProfileSerializer中使用它(作为嵌套序列化器):
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'
        )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接