Mysql-Sqlalchemy-ORM-多外键关联

创建表结构:orm_many_fk.py

from sqlalchemy import Integer, ForeignKey, String, Column,create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()#生成orm基类


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

    billing_address_id = Column(Integer, ForeignKey("address.id"))
    shipping_address_id = Column(Integer, ForeignKey("address.id"))

    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 "<%s >" % (self.street)
engine = create_engine("mysql+pymysql://root:521521@192.168.71.140/oldboy",
                       encoding='utf-8')  # 可以加echo=True显示数据

#Base.metadata.create_all(engine)

 操作数据库:增删改查等操作 orm.api.py

from day12 import orm_many_fk

from sqlalchemy.orm import sessionmaker

Session_class = sessionmaker(bind=orm_many_fk.engine)

Session =Session_class()#游标

'''插入数据'''
# addr1 = orm_many_fk.Address(street="Tiantongyuan",city="ChangPing",state="BeiJing")
# addr2 = orm_many_fk.Address(street="Wudaokou",city="HaiDian",state="BeiJing")
# addr3 = orm_many_fk.Address(street="YanJiao",city="LangFang",state="HB")
#
# Session.add_all([addr1,addr2,addr3])
# c1 = orm_many_fk.Customer(name="WanPang",billing_address=addr1,shipping_address=addr2)
# c2 = orm_many_fk.Customer(name="goupang",billing_address=addr3,shipping_address=addr3)

# Session.add_all([c1,c2])

'''查看数据'''
obj = Session.query(orm_many_fk.Customer).filter_by(name="goupang").first()
print(obj.name,obj.billing_address, obj.shipping_address)
Session.commit()

 

posted @ 2018-07-16 16:47  努力乄小白  阅读(143)  评论(0编辑  收藏  举报