Skip to content

Fixing missing base class in reflection docs, adding to reflection test #1283

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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