qg_java_17137
qg_java_17137

Reputation: 3589

How about create multi model instance through serializer?

How about create multi model instance through serializer?

I have a views.py:

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

Its serializer is this:

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. 

You see, my serializer, I override the create method, and I use for-loop to save the CloudServer instances to database.

But the create method must return a instance, what to do with that?

Because I access the view one time, to create the count times CloudServer instances, in my create method I have saved to database, what should I do then(in this line # But there must return a CloudServer instance.)?

Upvotes: 1

Views: 51

Answers (1)

origamic
origamic

Reputation: 1116

If CloudServer Model has count field, You mustn't use validated_data.pop() function.If It has, you must use get() function.

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)

Upvotes: 2

Related Questions