SQLAlchemy Declarative - SQL Server中的模式和外键/主键

时间:2015-05-29 20:01:34

标签: sql-server sqlalchemy

我正在努力创建属于SQL Server数据库中架构的表,并确保主键/外键正常工作。

我正在寻找一些代码示例,以说明如何完成此操作

1 个答案:

答案 0 :(得分:1)

这需要的成分是__table_args__并且在ForeignKey

上使用了模式前缀
DBSession = sessionmaker(bind=engine)
session = DBSession()

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

Base = declarative_base()

class Table1(Base):
    __tablename__ = 'table1'
    __table_args__ = {"schema": 'my_schema'}

    id = Column(Integer,primary_key = True)
    col1 = Column(String(150))
    col2 = Column(String(100))

    reviews = relationship("Table2", cascade = "delete")  

class Table2(Base):
    __tablename__ = 'table2'
    __table_args__ = {"schema": 'my_schema'}

    id = Column(Integer,primary_key = True)
    key = Column(Integer)
    col2 = Column(String(100))



    key = Column(Integer, ForeignKey("my_schema.table1.id"), index=True)  
    premise = relationship("Table1") 


Base.metadata.create_all(bind=engine)