diff --git a/docs/queries.rst b/docs/queries.rst index 50c5cb15..511321c9 100644 --- a/docs/queries.rst +++ b/docs/queries.rst @@ -116,11 +116,15 @@ Queries in Views If you write a Flask view function it's often very handy to return a 404 error for missing entries. Because this is a very common idiom, -Flask-SQLAlchemy provides a helper for this exact purpose. Instead of -:meth:`~sqlalchemy.orm.query.Query.get` one can use -:meth:`~Query.get_or_404` and instead of -:meth:`~sqlalchemy.orm.query.Query.first` :meth:`~Query.first_or_404`. -This will raise 404 errors instead of returning `None`:: +Flask-SQLAlchemy provides helpers for this exact purpose. + +Instead of :meth:`~sqlalchemy.orm.query.Query.get` one can use +:meth:`~Query.get_or_404`, instead of +:meth:`~sqlalchemy.orm.query.Query.first` use :meth:`~Query.first_or_404`, +and instead of :meth:`~sqlalchemy.orm.query.Query.one_or_none` use +:meth:`~Query.one_or_404`. + +These methods will raise 404 errors instead of returning `None`:: @app.route('/user/') def show_user(username): diff --git a/flask_sqlalchemy/__init__.py b/flask_sqlalchemy/__init__.py index 4de8be1b..be99577e 100644 --- a/flask_sqlalchemy/__init__.py +++ b/flask_sqlalchemy/__init__.py @@ -426,6 +426,14 @@ def first_or_404(self): if rv is None: abort(404) return rv + + def one_or_404(self): + """Like :meth:`one_or_none` but aborts with 404 if not found instead of returning ``None``.""" + + rv = self.one_or_none() + if rv is None: + abort(404) + return rv def paginate(self, page=None, per_page=None, error_out=True): """Returns ``per_page`` items from page ``page``.