确保 django 模型被正确保存



当使用它的 save 方法保存 django 模型时,有没有办法确保在保存过程中没有任何反应并向用户发送消息?我在想消息框架并尝试除了块?

try:
    model.save()
    add success message to message framework
except DatabaseError:
    add error message to message framework
except TransactionManagementError:
    add error message

这是正确的方法吗?另外,在尝试保存模型的新实例时,更有可能引发哪个异常?我对django相当陌生,所以要善待:)

我的方法是使用我所有模型都扩展的基本抽象模型,并在其中覆盖 save 方法以捕获异常和回滚事务:

class AbstractModel(models.Model):
    class Meta:
        abstract = True
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        try:
            super(AbstractModel, self).save(force_insert, force_update, using, update_fields)
        except IntegrityError as saveException:
            logger.exception('Rolling back transaction due to an error while saving %s...' % self.__class__.__name__)
            try:
                transaction.rollback()
            except Exception as rollbackException:
                logger.exception('Unable to rollback!')

您通常希望将其分为两个问题:

  • 内容问题,即您尝试在数据库中保存同一行两次,触发由数据库约束引起的错误。 这将引发一个可捕获的IntegrityError. 参见:https://docs.djangoproject.com/en/dev/ref/exceptions/#database-exceptions(Django 1.6+还有一些错误)。 您可能应该捕获这些并使用类似messages.error来通知用户。
  • 数据库已关闭或存在其他严重问题。 你可能应该避免捕捉错误,让 django 为你处理它,并显示你自己的 500 页,直到数据库重新上线。请参阅:https://docs.djangoproject.com/en/dev/howto/error-reporting/和 https://docs.djangoproject.com/en/dev/ref/urls/#handler500

相关内容

最新更新