[Answered ]-Are django models thread safe?

2👍

You need to elaborate a bit about what you mean with thread safe. If you’re not planning on using a lock, then of course it’s not thread safe. For instance,

s = SomeModel.objects.get(pk=1)
s.field = 2
s.save()

will obviously not be consistent if 3 threads are doing it at the same time. However, SomeModel.objects.filter(pk=1).update(field=2) is actually threadsafe. Use transaction.atomic() to maintain thread safety. Although, there could be a problem spawning alot of threads and connecting to the database at the same time, make sure you’re allowed to open as many connections as planned.

An efficient way to do this would be to have one thread that’s doing all the database interactions, while the other threads are doing calculations or whatever your plan is. Pass the objects on a Queue to synchronize.

Leave a comment