Assume you have a model called Blog
:
class Blog(models.Model):
title = models.CharField(max_length=255)
content = models.CharField(max_length=500)
and you want to insert 10 blogs in your database, so let's build our views:
class BlogApi(APIView):
def get(self, request):
for _ in range(10):
blog = Blog.objects.create(
title = 'Blog Title',
content = 'Blog Content'
)
return Response(status=status.HTTP_201_CREATED)
This will insert 10 times into the database with CPU time 268.63ms as you can see ๐
-> The debugging above from django-debug-toolbar
Now let's use bulk_create
to see the difference ๐
class BlogApi(APIView):
def get(self, request):
blog_list = [] # Empty list to save blog object on
for _ in range(10):
blog = Blog(
title = 'Blog Title',
content = 'Blog Content'
)
blog_list.append(blog)
Blog.objects.bulk_create(blog_list) # Use bulk_create to insert the list of blog objects
return Response(status=status.HTTP_201_CREATED)
Only 2 queries in 1.35ms with CPU time 156.79ms !!
That's awesome ๐
Read more about bulk_create()
& bulk_update()
from the the docs
Finally, thanks for reading and I hope you learned something new in Django ORM, have a lovely day ๐ผ
Top comments (0)