Menu Close

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

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.

Posted in Python, Python Answers