django-rest-framework-bulk
django-rest-framework-bulk copied to clipboard
Use bulk_create for bulk creation
DRF creates objects individually - which ends up being pretty slow if you post, say, 200 items to a "bulk" endpoint. Still better than the alternative, but still not great. It would be nice to use bulk_create instead.
Looking into this a little more, DRF is using individual saves because it's accounting for things like setting M2M values. It's also worth noting that unless you're using postgres (and a version of django that supports this) bulk_create doesn't set PKs on the created objects.
So if people want to do this right now, here's a ListSerializer that you can use for it:
from rest_framework_bulk import BulkListSerializer
class BulkCreateListSerializer(BulkListSerializer):
def create(self, validated_data):
ModelClass = self.child.Meta.model
return ModelClass.objects.bulk_create([
ModelClass(**attrs) for attrs in validated_data
])
Just use this wherever you would normally use BulkListSerializer. Caveats: doesn't support M2M, or anything else that requires individual creation. Also, PK setting is only enabled for postgres on django >= 1.10 (but that only matters if you need the pks)