This is what I have so far.
My serializer:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('field_1', 'field_2', 'field_3')
My ModelViewset
class MyViewSet(ModelViewSet):
serializer_class = MySerializer
model = MyModel
queryset = MyModel.objects.all().order_by('date_paid')
def create(self, request, *args, **kwargs):
many = True if isinstance(request.data, list) else False
serializer = MySerializer(data=request.data, many=many)
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)
My main concern is that when testing the endpoint to create multiple objects using the following payload, on the view the property request.data seem to be empty, as a result it returns errors of fields missing.
{
'data': [
{
'type': 'MySerializer',
'attributes': {
'field_1': 1,
'field_2': 0.05,
'field_3': 'abc'
}
},
{
'type': 'MySerializer',
'attributes': {
'field_1': 1,
'field_2': 0.05,
'field_3': 'abc'
}
},
{
'type': 'MySerializer',
'attributes': {
'field_1': 1,
'field_2': 0.05,
'field_3': 'abc'
}
}
]
}
However when using a single object instance:
{
'data': {
'type': 'MySerializer',
'attributes': {
'field_1': 1,
'field_2': 0.05,
'field_3': 'abc'
}
}
}
It seeems to work just fine and the object is created.
I have tried several ways to accomodate the payload:
- Placing the list of objects inside the
attributesfield. - Placing the list of instances directly on the
datafield but it returns either an object error, or and emptyrequest.data
How am I supposed to send the data for multiple objects, is it even possible, I have read in many articles that just by placing many=True on the serializer instance is enough to accomplish this but I just cant't get the data from the request.
Any step that I missed or another workaround?
EDIT
Forgot to mention two things
- that I'm using django rest framework json api library, could that be the reason why the data is empty?
- I placed dictionaries since I'm testing the endpoints and I use json.dumps(payload) when sending data.