【问题标题】:django restful api - how to serialize foreign keysdjango restful api - 如何序列化外键
【发布时间】:2018-12-11 06:01:05
【问题描述】:

我正在使用 django 1.8 和 djangorestframework==3.6.3。 我从文档中获取了模型示例:

https://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

这是我的序列化程序:

from rest_framework import serializers
from .models import *

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')


class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration', 'album')

这是我如何调用序列化程序:

def index(request):
    if Track.objects.all().count() == 0:
        album = Album.objects.create(album_name='something', artist='John')
        Track.objects.create(album=album, order=1, title='something', duration=1)

    print TrackSerializer(instance=Track.objects.all()[0]).data
    return render(request, 'index.html')

打印语句给我: {'duration': 1, 'album': 1, 'order': 1, 'title': u'something'} 为什么没有给我对应专辑的所有字段数据?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    在相应的示例中,他们习惯于返回 Album 的数据,而您尝试返回/打印 Track 的数据。

    因此,如果您尝试如下操作,它将按照 DRF 文档中的描述/显示打印/返回数据

    def index(request):
        if Track.objects.all().count() == 0:
            album = Album.objects.create(album_name='something', artist='John')
    
            print(AlbumSerializer(album).data)  # this will print the data as explianed in the doc
    
            Track.objects.create(album=album, order=1, title='something', duration=1)
    
        return render(request, 'index.html')

    如果您想向 album 显示详细信息,请创建一个新的专辑序列化程序 AlbumNewSerializer 并将其链接到 TrackSerializer 作为,

    class AlbumNewSerializer(serializers.ModelSerializer):
        class Meta:
            model = Album
            fields = ('album_name', 'artist')
    
    
    class TrackSerializer(serializers.ModelSerializer):
        album = AlbumNewSerializer()
    
        class Meta:
            model = Track
            fields = ('order', 'title', 'duration', 'album')

    注意:您可以使用 AlbumSerializer 代替 AlbumNewSerializer,但结果可能是丑陋的嵌套方式(未经测试..)

    【讨论】:

      【解决方案2】:

      我认为你需要这样做:

      class TrackSerializer(serializers.ModelSerializer):
          album = AlbumSerializer(…)
      
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        相关资源
        最近更新 更多