Django: how to do get_or_create() in a threadsafe way?

In my Django app very often I need to do something similar to get_or_create(). E.g.,

User submits a tag. Need to see if
that tag already is in the database.
If not, create a new record for it. If
it is, just update the existing
record.

But looking into the doc for get_or_create() it looks like it’s not threadsafe. Thread A checks and finds Record X does not exist. Then Thread B checks and finds that Record X does not exist. Now both Thread A and Thread B will create a new Record X.

This must be a very common situation. How do I handle it in a threadsafe way?

Answer

This must be a very common situation. How do I handle it in a threadsafe way?

Yes.

The “standard” solution in SQL is to simply attempt to create the record. If it works, that’s good. Keep going.

If an attempt to create a record gets a “duplicate” exception from the RDBMS, then do a SELECT and keep going.

Django, however, has an ORM layer, with it’s own cache. So the logic is inverted to make the common case work directly and quickly and the uncommon case (the duplicate) raise a rare exception.