Python SqlAlchemy链接表
所以我想用SQLAlchemy创建3个表Python SqlAlchemy链接表,python,sql,database,sqlalchemy,Python,Sql,Database,Sqlalchemy,所以我想用SQLAlchemy创建3个表 Obj obj_id | obj_type User user_id | obj_id | name | mail Society society_id | obj_id | name 让我们假设我推3个元素,我想要这样的东西: Obj obj_id | obj_type 1 | society 2 | user 3 | society User user_id | obj_id | name | mail 1
Obj
obj_id | obj_type
User
user_id | obj_id | name | mail
Society
society_id | obj_id | name
让我们假设我推3个元素,我想要这样的东西:
Obj
obj_id | obj_type
1 | society
2 | user
3 | society
User
user_id | obj_id | name | mail
1 | 2 | John | john.smith@700.com
Society
society_id | obj_id | name
1 | 1 | Google
2 | 3 | Facebook
如何构造代码并添加/提交以便链接表
class Obj(Base):
__tablename__ = 'objects'
obj_id = Column(Integer, primary_key=True)
obj_type = Column(String(30))
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer, primary_key=True)
obj_id = Column(Integer, ForeignKey('objects.obj_id'))
name = Column(String(100), default=None)
mail = Column(String(200), default=None)
objects = relationship("Obj", back_populates="users")
class Society(Base):
__tablename__ = 'society'
society_id = Column(Integer, primary_key=True)
obj_id = Column(Integer, ForeignKey("objects.obj_id"))
name = Column(String(100), default=None)
objects = relationship("Obj", back_populates="society")
people = relationship("People", back_populates="society")
您的表结构类似于,其中
objects.obj_type
为:
请注意,您不需要子类中的对象关系来将它们链接到相关的Obj。您可以像继承时一样访问父对象的属性
添加3个元素:
In [6]: session.add(User(name='John', mail='john.smith@700.com'))
In [7]: session.add_all([Society(name='Google'), Society(name='Facebook')])
In [8]: session.commit()
并检查是否可以查询所有OBJ:
In [9]: session.query(Obj).all()
Out[9]:
[<__main__.User at 0x7f37b5aaa780>,
<__main__.Society at 0x7f37b5aaab00>,
<__main__.Society at 0x7f37b5aaacc0>]
In [9]: session.query(Obj).all()
Out[9]:
[<__main__.User at 0x7f37b5aaa780>,
<__main__.Society at 0x7f37b5aaab00>,
<__main__.Society at 0x7f37b5aaacc0>]
In [10]: session.query(Obj.__table__).all()
Out[10]: [(1, 'user'), (2, 'society'), (3, 'society')]
In [11]: session.query(User.__table__).all()
Out[11]: [(1, 1, 'John', 'john.smith@700.com')]
In [12]: session.query(Society.__table__).all()
Out[12]: [(1, 2, 'Google'), (2, 3, 'Facebook')]