更新
问题在于,当每次更改将对象持久化到数据库中时,都会生成新的INSERT表达式。我需要的只是一个包含所有列的INSERT 。
#First **INSERT** request
plane.hangar.appen(hangar)
#Second **INSERT** request
users.planes.append(plane)
我有以下用SqlAlchemy描述的数据库结构。我要做的是在表“ users_planes_hangars
”中插入一条新记录。我正在尝试通过以下方式做到这一点:
plane= dbSession.query(Plane).filter(Plane.plane_id == planeId).first()
garage = dbSession.query(Hangar).filter(Hangar.hangar_id == hangarId).first()
plane.hangar.appen(hangar)
users.planes.append(plane)
dbSession.commit()
问题是执行的查询(下面的查询)不包括user_id
,它只包括plane_id
和hangar_id
。
INSERT INTO users_planes_hangars (plane_id, hangar_id) VALUES (%(plane_id)s, %(hangar_id)s)
RETURNING users_planes_hangars.user_id' {'hangar_id': 4, 'plane_id': 16}
|usersTabe| <--- |users_planes_hangars_table| ---> |planesTable|
|
\|/
|hangarsTable|
class User(object):
pass
class Plane(object):
pass
class Hangar(object):
pass
usersMeta = Table("user",
Column("user_id", Integer, primary_key = True)
)
mapper(User, usersMeta, properties = {
"planes": relationship(Plane, usersPlanesHangars)
})
planesMeta = Table("planes",
Column("plane_id", Integer, primary_key = True)
)
mapper(Plane, planesMeta, properties = {
"hangar": relationship(Hangar, usersPlanesHangars)
})
hangarMeta = Table("hangars",
Column("hangar_id", Integer, primary_key = True)
)
usersPlanesHangars = Table("users_planes_hangars",
Column("user_id", Integer, ForeinKey("users.user_id"), primary_key = True)
Column("plane_id", Integer, ForeinKey("planes.plane_id"), primary_key = True)
Column("hangar_id", Integer, ForeinKey("hangar.hangar_id"), primary_key = True)
)