1

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.)?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.