DEV Community

Mohamed Hamza
Mohamed Hamza

Posted on

Improve your Django query with bulk_create 👋

Assume you have a model called Blog:

class Blog(models.Model):
    title = models.CharField(max_length=255)
    content = models.CharField(max_length=500)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This will insert 10 times into the database with CPU time 268.63ms as you can see 👇
Image description

-> 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)
Enter fullscreen mode Exit fullscreen mode

How much this will cost?
Image description

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)