django restful api-如何序列化外键

时间:2018-12-11 06:01:05

标签: django django-rest-framework

我正在将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')

打印声明给我: {“持续时间”:1,“相册”:1,“订单”:1,“标题”:u“某物”} 为什么没有给我对应专辑的所有字段数据?

2 个答案:

答案 0 :(得分:2)

在相应的示例中,它们曾经用于返回 offersWithoutexcerpt: function(category) { if (!category.offers) return []; return category.offers .slice(category.largeBox ? 4 : 3, category.offers.length) .filter(function(offer) { var today = new Date().setHours(0, 0, 0, 0); var dateToBeMatchedString = offer["@_expires"]; if (!dateToBeMatchedString) return true; var dateToBeMatched = new Date( parseInt(dateToBeMatchedString.substring(6, 10)), parseInt(dateToBeMatchedString.substring(3, 5)), parseInt(dateToBeMatchedString.substring(0, 2)) ); return today <= dateToBeMatched; }); }, 的数据,而您试图返回/打印 Album 的数据。

因此,如果您尝试以下操作,它将按照DRF文档中的说明/所示打印/返回数据。

Track

如果您想显示真实到 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 并将其链接到{{1 }}

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') ,但结果可能嵌套在丑陋的位置时尚(未经测试..)

答案 1 :(得分:0)

我认为您需要执行以下操作:

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

    ...