zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    1、购买阿里云服务器
    struts2页面乱码解决方法
    struts第一次编写怎么都无法跳转页面
    时间转换与map集合
    struts2addActionError 、addFieldError、addActionMessage方法
    struts2基本流程
    struts2自定义类型转换器
    jsp聊天窗口随笔
    conn!=null与conn.isClosed的区别
    应用表单隐藏域进行提交
  • 原文地址:https://www.cnblogs.com/fuyuteng/p/9318505.html
Copyright © 2011-2022 走看看