" name="sm-site-verification"/>
侧边栏壁纸
博主头像
PySuper博主等级

千里之行,始于足下

  • 累计撰写 203 篇文章
  • 累计创建 14 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
Web

Django 嵌套序列化

PySuper
2020-09-18 / 0 评论 / 0 点赞 / 19 阅读 / 5208 字
温馨提示:
所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊

serializer.py

from .models import *
from rest_framework import serializers, fields


class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = ('id', 'artist', 'name', 'release_date', 'num_stars')


class MusicianSerializer(serializers.ModelSerializer):
    album_musician = AlbumSerializer(many=True)

    class Meta:
        model = Musician
        fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician')

    def create(self, validated_data):
        albums_data = validated_data.pop('album_musician')
        musician = Musician.objects.create(**validated_data)
        for album_data in albums_data:
            Album.objects.create(artist=musician, **album_data)
        return musician

    def update(self, instance, validated_data):
        albums_data = validated_data.pop('album_musician')
        albums = (instance.album_musician).all()
        albums = list(albums)
        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.instrument = validated_data.get('instrument', instance.instrument)
        instance.save()
        for album_data in albums_data:
            album = albums.pop(0)
            album.name = album_data.get('name', album.name)
            album.release_date = album_data.get('release_date', album.release_date)
            album.num_stars = album_data.get('num_stars', album.num_stars)
            album.save()
        return instance

POST

post如下数据到MusicianListView创建

{
    "first_name": "ganesh",
    "last_name": "xeno",
    "instrument": "Guitar",
    "album_musician": [
        {"name": "NEO", "release_date": "2017-07-07", "num_stars": 5},
        {"name": "NEO 2", "release_date": "2017-07-22", "num_stars": 4}
    ]
}

PUT

put方法更新操作MusicianListView

{
    "id": 1,
    "first_name": "ganesh",
    "last_name": "xeno",
    "instrument": "Guitar",
    "album_musician": [
        {"id": 1, "artist": 1, "name": "NEO", "release_date": "2017-07-07", "num_stars": 5},
        {"id": 2, "artist": 1, "name": "NEO 2", "release_date": "2017-07-22", "num_stars": 4}
    ]
}

示例

class SceneTaskSerializer(serializers.ModelSerializer):
    scene = SceneSerializer()

    class Meta:
        model = SceneTask
        fields = (
            'id', 'name', 'serivce_privider', "account", "biz_list", "ip_list", 
            "script_type", "input_display_list","script_param", "output_display_map", 
            "script_content", "script_timeout", "status", "rule_info", "scene",'creator', 
            'create_at', 'block_detail', 'refuse_detail'
        )
        required_field = ('serivce_privider')

    def create(self, validated_data):
        scene = validated_data.pop('scene')
        scene = Scene.objects.get(id=self.initial_data["scene"]["id"])
        return SceneTask.objects.create(scene=scene, **validated_data)

    def update(self, instance, validated_data):
        if validated_data.get("scene"):
            scene = validated_data.pop('scene')
            scene = Scene.objects.get(id=self.initial_data["scene"]["id"])
            scene_task = super(SceneTaskSerializer, self, ).update(instance, validated_data)
            scene_task.scene = scene
            scene_task.save()
            return scene_task
        return super(SceneTaskSerializer, self, ).update(instance, validated_data)

    def is_valid(self, raise_exception=False):
        if self.initial_data.get("scene"):
            instance = Scene.objects.get(id=self.initial_data["scene"])
            self.initial_data["scene"] = SceneSerializer(instance=instance).data
        return super(SceneTaskSerializer, self).is_valid(raise_exception)
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区