python 之sqlalchemy many to many

Posted 曾春云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 之sqlalchemy many to many相关的知识,希望对你有一定的参考价值。

 1 # -*- coding: utf-8 -*-
 2 """
 3 @author: zengchunyun
 4 """
 5 from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Table
 6 from sqlalchemy.orm import sessionmaker, relationship, backref
 7 from sqlalchemy.ext.declarative import declarative_base
 8 from sqlalchemy import create_engine
 9 
10 Base = declarative_base()
11 engine = create_engine(mysql+pymysql://root:[email protected]:3306/day11,echo=True)
12 
13 
14 
15 class Association(Base):
16     __tablename__ = association
17     left_id = Column(Integer, ForeignKey("left.id"), primary_key=True)
18     right_id = Column(Integer, ForeignKey("right.id"), primary_key=True)
19     extra_data = Column(String(50))
20     child = relationship("Child", back_populates="parents")
21     parent = relationship("Parent", back_populates="children")
22 
23 
24 class Parent(Base):
25     __tablename__ = left
26     id = Column(Integer, primary_key=True)
27     children = relationship("Association", back_populates=parent)
28 
29 class Child(Base):
30     __tablename__ = right
31     id = Column(Integer, primary_key=True)
32     parents = relationship("Association", back_populates="child")
33 
34 
35 Base.metadata.create_all(engine)
36 
37 DBSession = sessionmaker()
38 DBSession.configure(bind=engine)
39 session = DBSession()  # 打开数据连接
40 
41 
42 # 插入数据方式一
43 # p = Parent()
44 # c = Child()
45 # a = Association(extra_data="ss")
46 # a.parent = p
47 # a.child = c
48 # 插入数据方式二
49 c = Child()
50 a = Association(extra_data=dd)
51 a.parent = Parent()
52 c.parents.append(a)
53 
54 # 插入数据方式三
55 # p = Parent()
56 # a = Association(extra_data="some data")
57 # a.child = Child()
58 # p.children.append(a)
59 #
60 # for assoc in p.children:
61 #     print(assoc.extra_data)
62 #     print(assoc.child)
63 
64 
65 session.add(a)
66 session.commit()

 

 

第二种方式

上面的其它代码不变,只修改relationship关系,效果是一样的

 1 class Association(Base):
 2     __tablename__ = association
 3     left_id = Column(Integer, ForeignKey("left.id"), primary_key=True)
 4     right_id = Column(Integer, ForeignKey("right.id"), primary_key=True)
 5     extra_data = Column(String(50))
 6     child = relationship("Child", backref="parents")
 7     parent = relationship("Parent", backref="children")
 8 
 9 
10 class Parent(Base):
11     __tablename__ = left
12     id = Column(Integer, primary_key=True)
13 
14 class Child(Base):
15     __tablename__ = right
16     id = Column(Integer, primary_key=True)

 

以上是关于python 之sqlalchemy many to many的主要内容,如果未能解决你的问题,请参考以下文章

python 来自http://pythonhosted.org/Flask-SQLAlchemy/models.html#many-to-many-relationships

SqlAlchemy “Too many connections”

python中flask和sqlalchemy的多对多

sqlalchemy 如何使用 automap_base 生成(多对多)关系

Python之SqlAlchemy

python之sqlalchemy