Categories
Python Answers

How to create multiple model instances with the Python Django Rest Framework?

Spread the love

To create multiple model instances with the Python Django Rest Framework, we can create a serialize with many set to True.

For instance, we write

class ThingSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        many = kwargs.pop('many', True)
        super(ThingSerializer, self).__init__(many=many, *args, **kwargs)

    class Meta:
        model = Thing
        fields = ('loads', 'of', 'fields', )

to call the super class’ __init__ method with the many argument set to many.

If it’s True, then our serializer can accept multiple model instances.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *