Last modified: Jan 10, 2023 By Alexander Williams

How to use bulk_create() and bulk_update() Django methods

Yesterday, when I was coding a Django project, I wanted to update many model columns with different values with one query.
After searching in google, I founded bulk_create(), bulk_update() Django methods.

So, in this post, I'd like to share with you how to use bulk_create() and bulk_update() methods.

1. bulk_create()

bulk_create() is a method that creates the provided list of objects into the database with one query.

Example:

models.py


class posts(models.Model):
    title = models.CharField(max_length=300, unique=True)
    time = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.title    

let's say we want to add multiple different data into the above model


#articles
articles  = [posts(title="Hello python"), posts(title="Hello django"), posts(title="Hello bulk")]

#insert data
posts.objects.bulk_create(articles)

get QuerySet


>>> posts.objects.all()

<QuerySet [<posts: Hello python>, <posts: Hello django>, <posts: Hello bulk>]>

As you can see, we've added multiple data with one query.

2. bulk_update()

bulk_update() is a method that updates the given fields on the provided model instances with one query.

Syntax


bulk_update(objs, fields, batch_size=None)ΒΆ

Example:

In the above example, we'll update the data that we have just added.


update_queries = []

a = posts.objects.get(id=14)
b = posts.objects.get(id=15)
c = posts.objects.get(id=16)

#set update value
a.title="Hello python updated"
b.title="Hello django updated"
c.title="Hello bulk updated"

#append
update_queries.extend((a, b, c))

posts.objects.bulk_update(update_queries, ['title'])

Now let's see our queryset.


>>> posts.objects.all()


<QuerySet [<posts: Hello python updated>, <posts: Hello django updated>, <posts: Hello bulk updated>]>

summary

In this article, we'have learned how to use bulk_create() and bulk_update() methods, and i hope this post helps you.