码迷,mamicode.com
首页 > 编程语言 > 详细

python orm 多表查询

时间:2021-04-09 12:56:13      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:res   metadata   %s   cal   password   string   name   rom   return   

test_or.py

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

engine = create_engine("mysql+pymysql://root:Password6!@localhost/mingo")

Base = declarative_base()

book_m2m_author = Table(‘t_jetty_app_app_ip‘, Base.metadata,
                        Column(‘jettyapp_id‘,Integer,ForeignKey(‘t_jetty_app.id‘)),
                        Column(‘svrmachine_id‘,Integer,ForeignKey(‘t_svr_machine.id‘)),
                        )

class Book(Base):
    __tablename__ = ‘t_jetty_app‘
    id = Column(Integer,primary_key=True)
    name_en = Column(String(64))
    name = Column(String(128))
    t_svr_machine = relationship(‘Author‘,secondary=book_m2m_author,backref=‘t_jetty_app‘)

    def __repr__(self):
        return self.name

class Author(Base):
    __tablename__ = ‘t_svr_machine‘
    id = Column(Integer, primary_key=True)
    ip_address = Column(String(128))
    app_ip = Column(String(128))

    def __repr__(self):
        return self.ip_address



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

b1 = Book(name_en="aaa",name="测试一")
b2 = Book(name_en="bbb",name="测试二")
b3 = Book(name_en="ccc",name="测试三")
b4 = Book(name_en="ddd",name="测试四")

a1 = Author(ip_address="192.168.26.30",app_ip="192.168.26.30")
a2 = Author(ip_address="192.168.26.31",app_ip="192.168.26.31")
a3 = Author(ip_address="192.168.26.32",app_ip="192.168.26.32")
a4 = Author(ip_address="192.168.26.33",app_ip="192.168.26.33")
b1.t_svr_machine = [a1]
b2.t_svr_machine = [a2]
b3.t_svr_machine = [a3]
b4.t_svr_machine = [a4]
s.add_all([b1, b2, b3, b4, a1, a2, a3])

s.commit()

test_ormapi.py

from day_12 import  test_or
from sqlalchemy.orm import sessionmaker
Session_class = sessionmaker(bind=test_or.engine)
session = Session_class()
book_obj = session.query(test_or.Book).filter(test_or.Book.name_en=="cif-core").first()
print(book_obj.name,book_obj.t_svr_machine)
host_app = (" ".join(‘%s‘ %id for id in book_obj.t_svr_machine))
print(host_app)

session.commit()

  

python orm 多表查询

标签:res   metadata   %s   cal   password   string   name   rom   return   

原文地址:https://www.cnblogs.com/quemengqio/p/14632288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!