I would like to save and update multiple instances using the Django Rest Framework with one API call. For example, let's say I have a "Classroom" model that can have multiple "Teachers". If I wanted to create multiple teachers and later update all of their classroom numbers how would I do that? Do I have to make an API call for each teacher?
I know currently we can't save nested models, but I would like to know if we can save it at the teacher level. Thanks!
I know this was asked a while ago now but I found it whilst trying to figure this out myself.
It turns out if you pass
many=True
when instantiating the serializer class for a model, it can then accept multiple objects.This is mentioned here in the django rest framework docs
For my case, my view looked like this:
I didn't really want to go writing a load of boilerplate just to have direct control over the instantiation of the serializer and pass
many=True
, so in my serializer class I override the__init__
instead:Posting data to the list URL for this view in the format:
Created two resources with those details. Which was nice.
I think the best aprouch to respect the propoused architecture of the framework will be to create a mixin like this:
Then you can override the CreateModelMixin of ModelViewSet like this:
Now in the client you can work like this:
or
EDIT:
As Roger Collins suggest in her response is more clever to overwrite the get_serializer method than the 'create'.
You can simply overwrite the
get_serializer
method in your APIView and passmany=True
intoget_serializer
of the base view like so:Most straightforward method I've come across:
The Generic Views page in Django REST Framework's documentation states that the ListCreateAPIView generic view is "used for read-write endpoints to represent a collection of model instances".
That's where I would start looking (and I'm going to actually, since we'll need this functionality in our project soon as well).
Note also that the examples on the Generic Views page happen to use
ListCreateAPIView
.I couldn't quite figure out getting the request.DATA to convert from a dictionary to an array - which was a limit on my ability to Tom Manterfield's solution to work. Here is my solution:
And then I run the equivalent of this on the client: