database - Do transaction in Django make things faster -
i have django application.
this django application makes api call twitter , gets 100 recent tweets. need insert tweets database.
i have method act on 100 tweets. method has loop create model instance out of each tweet , call instance.save() on each instance separately.
i found things slower , thought transactions might make things faster.
so outside method added @method_decorator(transaction.atomic)
. still have loop created model instance , instance.save() method decorated transaction.atomic.
- is transaction.atomic supposed make insertions database faster me?
- will each instance.save() call still issue database call?
- if makes things faster, how?
in atomic transaction, series of database operations either all occur, or nothing occurs.
decorating method atomic
guarantee atomicity on database block of code within method. if method completed, changes committed database. if there exception, changes rolled back.
1. transactions not make code faster per use case. infact, guarantee either tweets
saved database or none of tweets
saved in case of exception.
2. yes, each instance.save()
call database call. so, there 100 database calls each time.
3. again, transactions won't make faster use case.
how make things faster then?
you can use django's bulk_create
create tweets
in single query.
tweet.objects.bulk_create([tweet1, tweet2, ...., tweet100]) # single query
this inserts list of tweet
objects database in efficient manner in 1 query.
Comments
Post a Comment