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

Oma*_*ali 3 python django django-rest-framework

我有一个用django_rest_framework. 我目前有一个对象是外键。当我发出一个 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
Run Code Online (Sandbox Code Playgroud)

有一个引用用户的用户外键。

网址:

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
Run Code Online (Sandbox Code Playgroud)

序列化器:

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

这是它的样子:

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/"
    }
]
Run Code Online (Sandbox Code Playgroud)

JPG*_*JPG 12

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

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