python alchemy

Solutions on MaxInterview for python alchemy by the best coders in the world

showing results for - "python alchemy"
Lorraine
08 Jan 2018
1 1from sqlalchemy import Column, Integer, String, ForeignKey, Table
2 2from sqlalchemy.orm import relationship, backref
3 3from sqlalchemy.ext.declarative import declarative_base
4 4
5 5Base = declarative_base()
6 6
7 7author_publisher = Table(
8 8    "author_publisher",
9 9    Base.metadata,
1010    Column("author_id", Integer, ForeignKey("author.author_id")),
1111    Column("publisher_id", Integer, ForeignKey("publisher.publisher_id")),
1212)
1313
1414book_publisher = Table(
1515    "book_publisher",
1616    Base.metadata,
1717    Column("book_id", Integer, ForeignKey("book.book_id")),
1818    Column("publisher_id", Integer, ForeignKey("publisher.publisher_id")),
1919)
2020
2121class Author(Base):
2222    __tablename__ = "author"
2323    author_id = Column(Integer, primary_key=True)
2424    first_name = Column(String)
2525    last_name = Column(String)
2626    books = relationship("Book", backref=backref("author"))
2727    publishers = relationship(
2828        "Publisher", secondary=author_publisher, back_populates="authors"
2929    )
3030
3131class Book(Base):
3232    __tablename__ = "book"
3333    book_id = Column(Integer, primary_key=True)
3434    author_id = Column(Integer, ForeignKey("author.author_id"))
3535    title = Column(String)
3636    publishers = relationship(
3737        "Publisher", secondary=book_publisher, back_populates="books"
3838    )
3939
4040class Publisher(Base):
4141    __tablename__ = "publisher"
4242    publisher_id = Column(Integer, primary_key=True)
4343    name = Column(String)
4444    authors = relationship(
4545        "Author", secondary=author_publisher, back_populates="publishers"
4646    )
4747    books = relationship(
4848        "Book", secondary=book_publisher, back_populates="publishers"
4949    )
50