From 3ecd038fe435cc62686360401252ca56a3a1dc85 Mon Sep 17 00:00:00 2001 From: Pamela Fox Date: Mon, 15 Jan 2024 07:58:14 -0800 Subject: [PATCH] Fixing missing base class in reflection docs, adding to reflection test (#1283) --- docs/models.rst | 9 +++++++-- tests/test_metadata.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/models.rst b/docs/models.rst index 6a471351..f9597643 100644 --- a/docs/models.rst +++ b/docs/models.rst @@ -139,14 +139,19 @@ defining the full model. Call the :meth:`~.SQLAlchemy.reflect` method on the extension. It will reflect all the tables for each bind key. Each metadata's ``tables`` attribute will contain the detected -table objects. +table objects. See :doc:`binds` for more details on bind keys. .. code-block:: python with app.app_context(): db.reflect() - class User: + # From the default bind key + class Book(db.Model): + __table__ = db.metadata.tables["book"] + + # From an "auth" bind key + class User(db.Model): __table__ = db.metadatas["auth"].tables["user"] In most cases, it will be more maintainable to define the model classes yourself. You diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 706609ae..8b54e5bc 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -162,3 +162,17 @@ def test_reflect(app: Flask) -> None: db.reflect() assert "user" in db.metadata.tables assert "post" in db.metadatas["post"].tables + + class User(db.Model): + __table__ = db.metadata.tables["user"] + + class Post(db.Model): + __table__ = db.metadatas["post"].tables["post"] + + db.session.add(User(id=1)) + users = db.session.execute(sa.select(User)).scalars().all() + assert len(users) == 1 + + db.session.add(Post(id=1)) + posts = db.session.execute(sa.select(Post)).scalars().all() + assert len(posts) == 1