I used to use allow_add_remove=True which was availabe in django rest 2.0 for writing nestable serializer but its not available in 3.0 and i am having hard time implementing it.
I want to do something like this
class UserSerialzier():
project = ProjectSerilaizer(many=True, allow_add_remove=True, read_only=False)
class ProjectSerialzier():
ideas = IdeaSerilaizer(many=True, allow_add_remove=True, read_only=False)
sources = SourceSerilaizer(many=True, allow_add_remove=True, read_only=False)
class IdeaSerialzier():
pass
class SourceSerialzier():
pass
Now i am not able to know how can i implement the allow_add_remove behavior in DRF 3.0
I am confused that do i need to override create
and update
method of UserSerializer
or i need to create separate IdeaListSerializer for every model
class IdeaListSerializer(serializers.ListSerializer):
def create(self, validated_data):
ideas = [Idea(**item) for item in validated_data]
return Ideas.objects.bulk_create(books)
Django bulk_create can help us optimize our application using a small number of database calls to save a lot of data. In other words, bulk_create can save multiple model instances into the database using only one database call.
To pass extra arguments to serializer Class in Python Django Rest Framework, we set the context argument to a dict with the values we want to pass to the serializer. to create a MyModelSerializer by calling MyModelSerializer with the context argument set to a dict. to get the context values with self.
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.
Yes you do need to override create
and update
methods of your UserSerializer
.
I've spent a lot of time trying to make nested writable serializers work with DRF 2.x and the more I fixed issues the more issues were risen with corner use cases.
Therefore Tom decided that it should be left up to the developer to handle the creation and updates.
The documentation provides an example for a 1 nesting level creation but it's the same for update and/or with more nesting level
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With