1

I have a Django 1.9 project and a REST view which receives from client-side a list objects, so the code looks like this:

Client-side object:

[
    {
       "field_a": "...",
       "field_b": "..."
    },
    {  
       "field_a": "...",
       "field_b": "..."
    }
]

The view:

@api_view(['POST'])
def send_sim_info(request):
   serializer = MySerializer(data=request.data, many=True)

So the serializer is of type ListSerializer

QUESTION:

How do I add fields to request.data in this case? In one object case, I would just write request.data['addition_field'] = my_value. What is the cleanest way to do a similar trick for the case of array?

1 Answer 1

3

It looks like you are using django-rest-framework. Would the following code work?

class MySerializer(serializers.ListSerializer):
    def create(self, validated_data):
        things = [Thing(**item) for item in validated_data]
        for thing in things:
            thing['additional_field'] = my_value
        return Thing.objects.bulk_create(things)

This is based on an example in the docs.

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.