问题描述
我有以下情况,
- 我需要插入到主表类型为'serial'的表(table1)中
- 现在,我需要插入到另一个包含table1主键作为外键的表(table2)中。
- 现在将两个插入都作为发生在同一笔交易中,生成的主键应在表2中引用。
让我们展示我尝试过的内容
Let us show what I tried
Base = declarative_base()
class Table1(Base):
__tablename__ = 'table1'
table1id= Column(Integer, primary_key=True)
name = Column(String)
class Table2(Base):
__tablename__ = 'table2'
table2id= Column(Integer, ForeignKey('table1.table1id'))
name = Column(String)
#
table1 = Table1(name='abc')
table2 = Table2(table2id=table1.table1id)
session.add(table1)
session.add(table2 )
session.commit()
当我运行这段代码时,table1id在表1中被插入为15,
在表2中被称为'null'。
When I ran this code table1id is inserted as 15 in table1,but it is refered as 'null' in table2.
推荐答案
在Python中创建模型对象时,该对象尚未刷新到数据库。如果是串行列,则数据库负责生成新值,因此生成前只是 None
。在语句中
When you create a model object in Python it is not yet flushed to the DB. In case of a serial column the DB is responsible for generating the new value, and so it is just None
before generation. In the statement
table2 = Table2(table2id=table1.table1id)
您只需阅读 None
并将其作为关键字参数 table2id 传递即可。为了获得一个值,您需要更改到数据库,因此您应该对操作进行一些重新排序:
you simply read that None
and pass it as the keyword argument table2id. In order to obtain a value you need to flush the changes to the database, so you should reorder your operations a bit:
table1 = Table1(name='abc')
session.add(table1)
# Flush the changes to the DB
session.flush()
table2 = Table2(table2id=table1.table1id)
session.add(table2)
session.commit()
SQLAlchemy还可以为您执行大多数操作,或者如果要在表1和表1之间定义 2,或者如果这实际上是。
SQLAlchemy could also perform most of this for you more or less automatically, if you'd define the relationships between table 1 and 2, or if this is actually an inheritance hierarchy.
这篇关于使用SqlAlchemy ORM将一列引用到其他表中的另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!