标签:opp pymysql 注意 for ring 实例 实例化 put session
一、实现联立
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String , Integer ,Column , ForeignKey
from sqlalchemy.orm import sessionmaker , relationship
engine = create_engine(‘mysql+pymysql://root@localhost/mydata?charset=utf8‘)#指定联哪一个数据库
Base = declarative_base() #创建一个基类
class Customer(Base):
‘‘‘创建一个表‘‘‘
__tablename__ = ‘customer‘
id = Column(Integer ,primary_key=True,autoincrement=True)
name = Column(String(32) , nullable=False)
contact= Column(Integer , nullable=False)
def __repr__(self):
return ‘<id ;%s , name : %s , contact : %s>‘%(self.id , self.name ,self.contact)
class Cus_shopping_list(Base):
‘‘‘创建一个表‘‘‘
__tablename__ = ‘cus_shopping_list‘
id = Column(Integer ,primary_key=True,autoincrement=True)
cid= Column(Integer , ForeignKey(Customer.id))
product= Column(String(32))
customer_info = relationship(‘Customer‘ , backref=‘shopping_list‘)
‘‘‘这个方法有点意思,可以通过像调用属性一样,实现关联表的信息调用,
相当于 session.query(a ,b ).filter(a.id=b.cid).all()过程
注意这个地方有两个小点,这个关系是双向的。同时relationship中的第一个parameter是一个类,不是表‘‘‘
def __repr__(self):
return ‘<id ;%s , cid : %s , product : %s>‘%(self.id , self.cid ,self.product)
Base.metadata.create_all(engine) #这个相当于实例化的过程
session_class = sessionmaker(bind=engine) #创建了一个会话类
session = session_class() #创建一个会话实例
c1 = Customer(name=‘ren‘ , contact=4545454)
c2 = Customer(name=‘eric‘ , contact=121212)
c3 = Customer(name=‘BULUSI‘ , contact=656565)
p1 = Cus_shopping_list(cid=1 , product=‘computer‘)
p2 = Cus_shopping_list(cid=1 , product=‘iphone‘)
p3 = Cus_shopping_list(cid=2 , product=‘Tsla‘)
# session.add_all([c1,c2,c3,p1,p2,p3 ])
data = session.query(Customer).filter(Customer.name==‘ren‘).first()
print(data)
print(data.shopping_list)
二、实现多个FK进行联立
这个准确的表达是需要通过多个字段联立才能定位到你想要得到的数据,其实真正的数据操作不一定需要建立两个外键来实现的。但是通过relationship这个建立的虚拟联系必须要建立在外键constraint上,所以就需要
建立两个外键
这里重新举例,明天重写一下这个例子
标签:opp pymysql 注意 for ring 实例 实例化 put session
原文地址:https://www.cnblogs.com/python-ERIC/p/9919036.html