If you are using MySQL, be sure to use the READ COMMITTED isolation level rather than REPEATABLE READ (the default), otherwise you may see cases where get_or_create will raise an IntegrityError but the object won’t appear in a subsequent get() call.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  def _create_object_from_params(self, lookup, params): """ Tries to create an object using passed params. Used by get_or_create and update_or_create """ try: with transaction.atomic(using=self.db): params = {k: v() if callable(v) else v for k, v in params.items()} obj = self.create(**params) return obj, True except IntegrityError: exc_info = sys.exc_info() try: return self.get(**lookup), False except self.model.DoesNotExist: pass six.reraise(*exc_info)

_create_object_from_params 做的事情就是开启一个事务，然后通过 insert 语句插入数据

 1 2 3  from django.db import transaction with transaction.atomic(): User.objects.get_or_create(nickname='xxx')