本文介绍了使用覆盖的to_representation更新嵌套的序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文



所以我有一个 AlbumSerializer 和一个嵌套的 TrackSerializer 。为了方便起见,我覆盖了 AlbumSerializer 的表示,以制成曲目的字典而不是列表。

  class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
字段=('id','order','title')
#直接向上跟踪轨道
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):
track = TrackSerializer(many = True)

class Meta:
模型=专辑
字段=('album_name','artist','tracks')

#制作轨道字典
def to_representation(self,instance):
表示形式= super()。to_representation(实例)
表示形式['tracks'] = {track ['id']:表示形式中的轨道跟踪on ['tracks']}
返回表示

#使用专辑端点
def update(self,instance,validated_data)更新轨道:
validated_data中的轨道['tracks']
obj,创建= Track.objects.update_or_create(
album_id = track ['album_id'],
order = track ['order'],
默认= {'title':track ['title']}

返回实例



问题



现在,当我尝试更新专辑(包括某些曲目标题)时,我会收到预期的项目列表但输入的类型为 \dict



问题



我如何使DRF接受字典而不是列表(如果有曲目)? / p>

更新:刚刚了解了。似乎正是我所需要的。

解决方案

在更新功能中,您是:




  • 尝试使用update_or_create循环播放类似列表的字典

  • ,这将导致创建重复的曲目



这是一个错误固定代码::

  def更新(自身,实例,validate_data):
为trackid,在validated_data ['tracks']。items()中跟踪:
obj = Track.objects.filter(id = trackid)
,如果obj:
obj [0]。 album_id = track ['album_id']
obj [0] .order = track ['order']
obj [0] .title = title = track ['title']
obj [ 0] .save()
其他:
Track.objects.create(
album_id = track ['album_id'],
order = track ['order'],
title = track ['title'])
返回实例


Context

So i have an AlbumSerializer with a nested TrackSerializer. For convenience on the frontend I overwrite the representation of AlbumSerializer to make a dictionary of the tracks instead of a list.

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

Problem

Now when i try to update the album, including some track titles, i receive Expected a list of items but got type \"dict\". Which makes sense.

Question

How can i make DRF accept dictionaries instead of a list if tracks ?

Update: Just learned about drf-rw-serializers. Seems exactly what i need.

解决方案

in update function, you are:

  • trying to loop a dictionary like a list
  • using update_or_create, this will lead to create duplicate tracks

Here is an error fixed code::

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

这篇关于使用覆盖的to_representation更新嵌套的序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:34