SQLAlchemy 声明性 - SQL Server 中的架构和外键/主键 [英] SQLAlchemy Declarative - schemas in SQL Server and foreign/primary keys

查看:41
本文介绍了SQLAlchemy 声明性 - SQL Server 中的架构和外键/主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm struggling to create tables that belong to a schema in a SQL Server database, and ensuring that primary/foreign keys work correctly.

我正在寻找一些代码示例来说明这是如何完成的

I'm looking for some examples of code to illustrate how this is done

推荐答案

为此需要的成分是 __table_args__ForeignKey 上架构前缀的使用>

The ingredients needed for this are __table_args__ and the use of the schema prefix on the 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)

这篇关于SQLAlchemy 声明性 - SQL Server 中的架构和外键/主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆