美文网首页
drf让序列化器支持更新创建、更新外键示例

drf让序列化器支持更新创建、更新外键示例

作者: 仁安天下 | 来源:发表于2019-11-28 19:49 被阅读0次
    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)
    
    

    重写了is_valid、create、update方法,其中scene是scene_task的外键

    相关文章

      网友评论

          本文标题:drf让序列化器支持更新创建、更新外键示例

          本文链接:https://www.haomeiwen.com/subject/mtkiwctx.html