如何通过序列化程序创建多模型实例?

2024-09-27 23:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过序列化程序创建多模型实例

我有一个观点.py:

class CloudServerCreateAPIView(CreateAPIView):
    """
    Create CloudServer
    """
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

其序列化程序如下:

class CloudServerCreateSerializer(ModelSerializer):

    count = serializers.IntegerField() 

    class Meta:
        model = CloudServer
        exclude = [
            'expiration_time',
            'buytime',
            'availablearea',
            'profile',
        ]

    def create(self, validated_data):

        count = validated_data.pop("count")
        for _ in range(0, count):
            # create the CloudServer instance, then save to database. And other logic stuff
        # But there must return a CloudServer instance. 

你看,我的序列化程序重写了create方法,并使用for循环将CloudServer实例保存到数据库中

但是create方法必须返回一个实例,该怎么办

因为我只访问了一次视图,要创建counttimes CloudServer实例,在我保存到数据库的create方法中,我应该做什么(在这一行# But there must return a CloudServer instance.


Tags: 实例方法instance程序fordata序列化count
1条回答
网友
1楼 · 发布于 2024-09-27 23:24:51

如果CloudServer模型有count字段,则不能使用已验证的\u data.pop()函数。如果有,则必须使用get()函数。 你知道吗

class CloudServerCreateSerializer(ModelSerializer):

    count = serializers.IntegerField() 

    class Meta:
        model = CloudServer
        exclude = [
            'expiration_time',
            'buytime',
            'availablearea',
            'profile',
        ]

    def create(self, validated_data):

        count = validated_data.pop("count")
        for _ in range(0, count):
            # create the CloudServer instance, then save to database. And other logic stuff

        return super(CloudServerCreateSerializer, self).create(validated_data)

相关问题 更多 >

    热门问题