Created
March 12, 2017 17:14
-
-
Save evangilo/9e1189613e5749b211308db5a8bf039c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from sqlalchemy import create_engine, Column, ForeignKey, Table, types | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref | |
| engine = create_engine("postgresql://<user>:<password>@localhost:5432/test", echo=False) | |
| Base = declarative_base() | |
| session = scoped_session(sessionmaker(bind=engine)) | |
| session.bind.execute("CREATE SCHEMA IF NOT EXISTS authors") | |
| session.bind.execute("CREATE SCHEMA IF NOT EXISTS books") | |
| # Fake models, dont use a table by schema :) | |
| # Models created only for tests | |
| class Book(Base): | |
| __tablename__ = "books" | |
| __table_args__ = {"schema": "books"} | |
| id = Column(types.Integer, primary_key=True) | |
| name = Column(types.String(255)) | |
| def __repr__(self): | |
| return "<Book(name=%r)>" % self.name | |
| class Author(Base): | |
| __tablename__ = "authors" | |
| __table_args__ = {'schema': 'authors'} | |
| id = Column(types.Integer, primary_key=True) | |
| name = Column(types.String(255)) | |
| books = relationship('Book', secondary=lambda: author_books, backref='authors') | |
| def __repr__(self): | |
| return "<Author(name=%r)>" % self.name | |
| author_books = Table("author_books", Base.metadata, | |
| Column("autor_id", types.Integer, ForeignKey(Author.__table__.c.id)), | |
| Column("book_id", types.Integer, ForeignKey(Book.__table__.c.id)), | |
| schema="authors") | |
| Base.metadata.create_all(engine) | |
| book = Book(name="A Song of Ice and Fire") | |
| author = Author(name="George R. R. Martin") | |
| author.books.append(book) | |
| session.add_all([author, book]) | |
| session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment