Skip to content

Commit

Permalink
Fixing missing base class in reflection docs, adding to reflection te…
Browse files Browse the repository at this point in the history
…st (#1283)
  • Loading branch information
pamelafox authored Jan 15, 2024
1 parent 91d3932 commit 3ecd038
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions docs/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 3ecd038

Please sign in to comment.