【问题标题】:Update nested serializer with an overwritten to_representation使用覆盖的 to_representation 更新嵌套序列化程序
【发布时间】:2019-11-14 00:59:31
【问题描述】:

上下文

所以我有一个带有嵌套TrackSerializerAlbumSerializer。为了在前端方便,我覆盖了AlbumSerializer 的表示,以制作曲目字典而不是列表。

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('id', 'order', 'title')
    # directly upsert tracks
    def create(self, validated_data):
            obj, created = Track.objects.update_or_create(
            album_id= validated_data['album_id'],
            order=validated_data['order'],
            defaults={'title': validated_data['title']}
            )
            return obj


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

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

    # make a dictionary of the tracks
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['tracks'] = {track['id']: track for track in representation['tracks']}
        return representation

    #update tracks with the album endpoint
    def update(self, instance, validated_data):
        for track in validated_data['tracks']
            obj, created = Track.objects.update_or_create(
            album_id= track['album_id'],
            order=track['order'],
            defaults={'title': track['title']}
            )
        return instance

问题

现在,当我尝试更新专辑(包括一些曲目标题)时,我会收到Expected a list of items but got type \"dict\"。这是有道理的。

问题

如何让 DRF 接受字典而不是曲目列表?

更新:刚刚了解了drf-rw-serializers。似乎正是我需要的。

【问题讨论】:

  • 你为什么在forloop里面使用return obj
  • 谢谢!做了一些复制粘贴。编辑了帖子。对此感到抱歉。

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


【解决方案1】:

在更新功能中,你是:

  • 试图像列表一样循环字典
  • 使用 update_or_create,这将导致创建重复的轨道

这是一个错误修复代码::

def update(self, instance, validated_data):
    for trackid, track in validated_data['tracks'].items():
        obj = Track.objects.filter(id = trackid)
        if obj:
            obj[0].album_id = track['album_id']
            obj[0].order = track['order']
            obj[0].title = title= track['title']
            obj[0].save()
        else:
            Track.objects.create(
                album_id= track['album_id'],
                order=track['order'],  
                title= track['title'])
    return instance

【讨论】:

  • 谢谢!但你领先一步:这不会阻止错误"Expected a list of items but got type \"dict\"."
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
相关资源
最近更新 更多