序列化器返回对象而不是字段

时间:2018-09-16 17:25:10

标签: django django-models django-rest-framework django-views django-serializer

使用Django 2.1 / Django Rest Framework。

我正在接收DRF而不是实际字段输出的Model对象。

我想收到audio_links和release_artists表的所有项目。

这就是我所拥有的。

输出

{ "title": "Attack The Dancefloor Volume Two", "audiolinks": [ "AudioLinks object (55708)", "AudioLinks object (55709)", "AudioLinks object (55710)", "AudioLinks object (55711)" ], "releaseartists": [ "ReleaseArtists object (140)", "ReleaseArtists object (141)" ] }

models.py

class AudioLinks(models.Model):
    release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id', related_name='audiolinks')
    track_number = models.IntegerField()
    class Meta:
        managed = False
        db_table = 'audio_links'

class ReleaseArtists(models.Model):
    release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id', related_name='releaseartists')
    artists = models.CharField(max_length=100)

    class Meta:
        managed = False
        db_table = 'release_artists'

views.py

class ListReleaseDetailView(generics.RetrieveUpdateDestroyAPIView):

    queryset = ReleasesAll.objects.all()
    serializer_class = ReleasesSerializer
    def get(self, request, *args, **kwargs):
        try:
            a_release = self.queryset.prefetch_related('releaseartists','audiolinks').get(pk=kwargs['release_id'])
            return Response(ReleasesSerializer(a_release).data)

        except ReleasesAll.DoesNotExist:
            return Response(
                data = {
                    "message": "{} does not exist".format(kwargs["release_id"])
                },
                status=status.HTTP_404_NOT_FOUND
            )

serializers.py

class ReleasesSerializer(serializers.ModelSerializer):
    audiolinks = serializers.StringRelatedField(many=True)
    releaseartists = serializers.StringRelatedField(many=True)

    class Meta:
        model = ReleasesAll
        fields = ('title','audiolinks','releaseartists')

1 个答案:

答案 0 :(得分:4)

*.xls提供模型上定义的serializers.stringRelatedField方法的输出。

因此,您将获得“ __str__”和“ AudioLinks object (55708)”,这是任何模型的默认ReleaseArtists object (141)表示形式。

为了获取所有字段,您必须为与所需字段相关的每个其他模型定义序列化器,例如:

__str__

然后:

class AudioLinksSerializer(serializers.ModelSerializer):
    class Meta:
        model = AudioLinks
        fields = ('__all__')

class ReleaseArtistsSerializer(serializers.ModelSerializer):
    audiolinks = serializers.StringRelatedField(many=True)
    releaseartists = serializers.StringRelatedField(many=True)

    class Meta:
        model = ReleaseArtists
        fields = ('__all__')

这足以使您获得所有字段。

***而且按照Django约定,您还需要以单数形式命名模型,即class ReleasesSerializer(serializers.ModelSerializer): audiolinks = AudioLinksSerializer(many=True) releaseartists = ReleaseArtistsSerializer(many=True) class Meta: model = ReleasesAll fields = ('title','audiolinks','releaseartists') AudioLink。这样,您可以将模型视为单个对象。当您尝试获取ReleaseArtist时会更容易,因为您会想到“很多AudioLink对象,而我却很少”