Python sqlalchemy orm 多外鍵關聯

 多外鍵關聯mysql

注:在兩個表之間進行多外鍵連接sql

 

如圖:數據庫

 

案例:session

# 建立兩張表並添加外鍵主鍵socket

# 調用Column建立字段 加類型
from sqlalchemy import Integer, ForeignKey, String, Column

# 調用基類Base
from sqlalchemy.ext.declarative import declarative_base

# 調用操做連接,反查
from sqlalchemy.orm import relationship

# 調用連接數據庫
from sqlalchemy import create_engine

Base = declarative_base()

class Customer(Base):
    __tablename__ = 'customer'
    id = Column(Integer, primary_key=True)
    name = Column(String(64))

    # 以Address表id字段 設置兩個外鍵
    billing_address_id = Column(Integer, ForeignKey("address.id"))
    shipping_address_id = Column(Integer, ForeignKey("address.id"))

    # relationship -容許你在Student表裏經過backref字段反向查出全部它在表裏的關聯項-
    # foreign_keys=綁定外鍵 屢次relationship 反差會識別不出指定數據因此添加foreign_keys參數。
    billing_address = relationship("Address",foreign_keys=[billing_address_id])
    shipping_address = relationship("Address",foreign_keys=[shipping_address_id])

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    street = Column(String(64))
    city = Column(String(64))
    state = Column(String(64))

    # 返回一個能夠用來表示對象的可打印字符串
    def __repr__(self):
        return self.street


# encoding='utf-8' 連接字符集 ,echo=True 把全部信息打印出來
engine = create_engine("mysql+pymysql://root:123456@192.168.1.100/xiang",encoding='utf-8',
                       #echo=True
                       )

#---------------1.建立表-----------------#
# 建立表結構
Base.metadata.create_all(engine)
#---------------------------------------#

 

# 插入表內字段數據,測試訪問ide

from www import orm_fk
from sqlalchemy.orm import sessionmaker

# bind=engine 綁定engine socket實例
Session_class = sessionmaker(bind=orm_fk.engine)

# 生成session實例,如同pymysql內的cursor
Session = Session_class()


#---------------2.寫入數據-----------------#

# 寫入數據
# addr1 = orm_fk.Address(street="Tiantongyuan",city="ChangPing",state="BJ")
# addr2 = orm_fk.Address(street="Wudaokou",city="Haidian",state="BJ")
# addr3 = orm_fk.Address(street="Yanjiao",city="Langfang",state="HB")

# 插入數據
# Session.add_all([addr1,addr2,addr3])

# 寫入數據 並調用 Address字段插入數據 爲 Customer數據
# c1 = orm_fk.Customer(name="kevin",billing_address=addr1,shipping_address=addr2)
# c2 = orm_fk.Customer(name="Jack",billing_address=addr3,shipping_address=addr3)

# 插入數據
# Session.add_all([c1,c2])
#---------------------------------------#


#---------------3.查詢數據-----------------#

# 取出Customer內的 內存對象
obj = Session.query(orm_fk.Customer).filter(orm_fk.Customer.name=="kevin").first()

# 經過內存 調用第一行name字段數據,
# 調用billing_address對應外鍵id的對應數據,
# 調用obj.shipping_address對應外鍵id的對應數據。
print(obj.name,obj.billing_address,obj.shipping_address)
#---------------------------------------#


# 執行事務
Session.commit()
# 表customer
+----+-------+--------------------+---------------------+
| id | name  | billing_address_id | shipping_address_id |
+----+-------+--------------------+---------------------+
|  1 | kevin |                  1 |                   2 |
|  2 | Jack  |                  3 |                   3 |
+----+-------+--------------------+---------------------+

# 表address
+----+--------------+-----------+-------+
| id | street       | city      | state |
+----+--------------+-----------+-------+
|  1 | Tiantongyuan | ChangPing | BJ    |
|  2 | Wudaokou     | Haidian   | BJ    |
|  3 | Yanjiao      | Langfang  | HB    |
+----+--------------+-----------+-------+
數據庫測試
相關文章
相關標籤/搜索