Edgar Navasardyan
Edgar Navasardyan

Reputation: 4511

Django REST - adding custom fields to request.data in case of array of objects

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?

Upvotes: 1

Views: 1657

Answers (1)

Laurent S
Laurent S

Reputation: 4326

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.

Upvotes: 3

Related Questions