SQLAlchemy Declarative - SQL Server schemas and foreign / primary keys

I am trying to create tables that belong to a schema in a SQL Server database and make sure the primary / foreign keys are working correctly.

I am looking for some code examples to illustrate how this is done

+3


source to share


1 answer


The ingredients required for this __table_args__

and the use of the schema prefix onForeignKey



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)

      

+1


source







All Articles