Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i bulk create in django rest serializer

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)
like image 863
John Kaff Avatar asked Nov 20 '15 12:11

John Kaff


People also ask

What is bulk create in Django?

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.

How do I pass extra data to a serializer?

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.

Which class allows you to automatically create a serializer?

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.


1 Answers

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

like image 151
Linovia Avatar answered Sep 18 '22 14:09

Linovia