其他分享
首页 > 其他分享> > day12_04 orm_manay_fk

day12_04 orm_manay_fk

作者:互联网

orm_manay_fk.py

# Author:Adminone

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

Base = declarative_base()

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 "<street:%s>" % (self.street)

engine = create_engine("mysql+pymysql://root:alex3714@192.168.56.12/oldboy",
                       encoding='utf-8')#,echo=True)

Base.metadata.create_all(engine)  # 创建表结构

orm_manay_fk_api.py

# Author:Adminone

import orm_manay_fk
from sqlalchemy.orm import sessionmaker, relationship


Session_class = sessionmaker(bind=orm_manay_fk.engine)  # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
session = Session_class()  # 生成session实例

#数据插入
'''
addr1 = orm_manay_fk.Address(street="Tiantongyuan", city="chuangPing",state="BJ")
addr2 = orm_manay_fk.Address(street="Wudaokou", city="HaiDian",state="BJ")
addr3 = orm_manay_fk.Address(street="Yanjiao", city="LangFang",state="HB")

session.add_all([addr1,addr2,addr3])
c1 = orm_manay_fk.Customer(name="Alex",billing_address=addr1,shipping_address=addr2)
c2 = orm_manay_fk.Customer(name="Jack",billing_address=addr3,shipping_address=addr3)

session.add_all([c1,c2])
session.commit()
'''

#信息查询
obj = session.query(orm_manay_fk.Customer).filter(orm_manay_fk.Customer.name=="alex").first()
print(obj.name,obj.billing_address,obj.shipping_address)

session.commit()

标签:manay,Column,session,orm,address,fk
来源: https://www.cnblogs.com/netflix/p/14855724.html