zoukankan      html  css  js  c++  java
  • Python3-sqlalchemy-orm 创建多表关联表带外键

    #-*-coding:utf-8-*-
    #__author__ = "logan.xu"
    
    
    import sqlalchemy
    from sqlalchemy import create_engine,func
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column,Integer,String,ForeignKey,DATE
    from sqlalchemy.orm import sessionmaker,relationship
    
    
    engine=create_engine("mysql+pymysql://root:12345678@localhost/news",encoding='utf-8',echo=True)
    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
    
    
    
    #---------------1.创建表-----------------#
    # 创建表结构
    Base.metadata.create_all(engine)
    #---------------------------------------#
    
    # bind=engine 绑定engine socket实例
    #Session_class = sessionmaker(bind=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(Customer).filter(Customer.name=="kevin").first()
    
    # 通过内存 调用第一行name字段数据,
    # 调用billing_address对应外键id的对应数据,
    # 调用obj.shipping_address对应外键id的对应数据。
    #print(obj.name,obj.billing_address,obj.shipping_address)
    #---------------------------------------#
    
    
    # 执行事务
    #Session.commit()
    /Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/test_1/orm_api.py
    2019-01-08 19:07:49,013 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
    2019-01-08 19:07:49,013 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,015 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
    2019-01-08 19:07:49,015 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,017 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
    2019-01-08 19:07:49,017 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,018 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
    2019-01-08 19:07:49,018 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,020 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
    2019-01-08 19:07:49,020 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,021 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
    2019-01-08 19:07:49,021 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:07:49,022 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) 
    COLLATE utf8mb4_bin AS anon_1
    2019-01-08 19:07:49,022 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:07:49,023 INFO sqlalchemy.engine.base.Engine DESCRIBE `customer` 2019-01-08 19:07:49,023 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:07:49,024 INFO sqlalchemy.engine.base.Engine DESCRIBE `address` 2019-01-08 19:07:49,024 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:07:49,030 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2019-01-08 19:07:49,031 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s) 2019-01-08 19:07:49,031 INFO sqlalchemy.engine.base.Engine {'street': 'tiantongyuan', 'city': 'changping', 'state': 'BJ'} 2019-01-08 19:07:49,032 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s) 2019-01-08 19:07:49,032 INFO sqlalchemy.engine.base.Engine {'street': 'wudaokou', 'city': 'haidian', 'state': 'BJ'} 2019-01-08 19:07:49,033 INFO sqlalchemy.engine.base.Engine INSERT INTO address (street, city, state) VALUES (%(street)s, %(city)s, %(state)s) 2019-01-08 19:07:49,033 INFO sqlalchemy.engine.base.Engine {'street': 'yanjiao', 'city': 'langfang', 'state': 'BJ'} 2019-01-08 19:07:49,034 INFO sqlalchemy.engine.base.Engine INSERT INTO customer (name, billing_address_id, shipping_address_id) VALUES (%(name)s,
    %(billing_address_id)s, %(shipping_address_id)s) 2019-01-08 19:07:49,034 INFO sqlalchemy.engine.base.Engine {'name': 'Alex', 'billing_address_id': 1, 'shipping_address_id': 2} 2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine INSERT INTO customer (name, billing_address_id, shipping_address_id) VALUES (%(name)s,
    %(billing_address_id)s, %(shipping_address_id)s) 2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine {'name': 'Jack', 'billing_address_id': 3, 'shipping_address_id': 3} 2019-01-08 19:07:49,035 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
    mysql> show tables;
    +----------------+
    | Tables_in_news |
    +----------------+
    | address        |
    | customer       |
    | student        |
    | study_record   |
    | user           |
    +----------------+
    5 rows in set (0.00 sec)
    
    mysql> select * from customer;
    +----+------+--------------------+---------------------+
    | id | name | billing_address_id | shipping_address_id |
    +----+------+--------------------+---------------------+
    |  1 | Alex |                  1 |                   2 |
    |  2 | Jack |                  3 |                   3 |
    +----+------+--------------------+---------------------+
    2 rows in set (0.00 sec)
    
    mysql> select * from address;
    +----+--------------+-----------+-------+
    | id | street       | city      | state |
    +----+--------------+-----------+-------+
    |  1 | tiantongyuan | changping | BJ    |
    |  2 | wudaokou     | haidian   | BJ    |
    |  3 | yanjiao      | langfang  | BJ    |
    +----+--------------+-----------+-------+
    3 rows in set (0.00 sec)
    #查询

    #
    -*-coding:utf-8-*- #__author__ = "logan.xu" from test_1 import orm_many_fk from sqlalchemy.orm import sessionmaker Session_class=sessionmaker(bind=orm_many_fk.engine) #创建与数据库的链接 session= Session_class() #生成session实例 #cursor #addr1=orm_many_fk.Address(street="tiantongyuan",city="changping",state="BJ") #addr2=orm_many_fk.Address(street="wudaokou",city="haidian",state="BJ") #add#r3=orm_many_fk.Address(street="yanjiao",city="langfang",state="BJ") # #session.add_all([addr1,addr2,addr3]) #c1= orm_many_fk.Customer(name="Alex",billing_address=addr1,shipping_address=addr2) #c2= orm_many_fk.Customer(name="Jack",billing_address=addr3,shipping_address=addr3) #session.add_all([c1,c2]) #查询 obj=session.query(orm_many_fk.Customer).filter(orm_many_fk.Customer.name=="alex").first() print(obj.name,obj.billing_address,obj.shipping_address) session.commit()
    /Users/drizzle/PycharmProjects/2018-12-03/venv/bin/python /Users/drizzle/PycharmProjects/2018-12-03/test_1/orm_api.py
    2019-01-08 19:15:17,840 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
    2019-01-08 19:15:17,840 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,842 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
    2019-01-08 19:15:17,842 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
    2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
    2019-01-08 19:15:17,844 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,847 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
    2019-01-08 19:15:17,847 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,848 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
    2019-01-08 19:15:17,848 INFO sqlalchemy.engine.base.Engine {}
    2019-01-08 19:15:17,849 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) 
    COLLATE utf8mb4_bin AS anon_1
    2019-01-08 19:15:17,849 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:15:17,850 INFO sqlalchemy.engine.base.Engine DESCRIBE `customer` 2019-01-08 19:15:17,850 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:15:17,851 INFO sqlalchemy.engine.base.Engine DESCRIBE `address` 2019-01-08 19:15:17,851 INFO sqlalchemy.engine.base.Engine {} 2019-01-08 19:15:17,857 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2019-01-08 19:15:17,858 INFO sqlalchemy.engine.base.Engine SELECT customer.id AS customer_id, customer.name AS customer_name,
    customer.billing_address_id AS customer_billing_address_id, customer.shipping_address_id AS customer_shipping_address_id FROM customer WHERE customer.name
    = %(name_1)s LIMIT %(param_1)s 2019-01-08 19:15:17,858 INFO sqlalchemy.engine.base.Engine {'name_1': 'alex', 'param_1': 1} 2019-01-08 19:15:17,859 INFO sqlalchemy.engine.base.Engine SELECT address.id AS address_id, address.street AS address_street,
    address.city AS address_city, address.state AS address_state FROM address WHERE address.id
    = %(param_1)s 2019-01-08 19:15:17,860 INFO sqlalchemy.engine.base.Engine {'param_1': 1} 2019-01-08 19:15:17,861 INFO sqlalchemy.engine.base.Engine SELECT address.id AS address_id, address.street AS address_street,
    address.city AS address_city, address.state AS address_state FROM address WHERE address.id
    = %(param_1)s 2019-01-08 19:15:17,861 INFO sqlalchemy.engine.base.Engine {'param_1': 2} Alex tiantongyuan wudaokou 2019-01-08 19:15:17,862 INFO sqlalchemy.engine.base.Engine COMMIT Process finished with exit code 0
  • 相关阅读:
    windows10的子系统linux(wsl)
    关于js的比较
    关于parseInt,很神奇
    vue修改数组元素通过arr[0]=val的方式不生效
    wps表格 VLookUp 函数
    青年大学习_收集截图方案
    个人记录_uwsgi,nginx与django之间的关系以及各自的作用
    Ubuntu16.04系统中创建新用户
    idea 启动或debug springboot web项目特别慢的解决方案
    利用Aop实现动态分库分表
  • 原文地址:https://www.cnblogs.com/drizzle-xu/p/10240916.html
Copyright © 2011-2022 走看看