基于记录数据的SqlAlchemy模型关联
有一个 info
表,它与 car
表或 suv
表有关系。
它在 info.type
字段中指定。
那么如何根据记录的类型数据动态创建关联呢?
class Info(Base):
item_id = Column(ForeignKey('cars-or-suvs-table.id'))
type = Column(String())
class Car(Base):
- data -
info = relationship('Info', backref="car")
class Suv(Base):
- data -
info = relationship('Info', backref="suv")
编辑:我的表已经填充了数据,所以我无法更改数据库架构。
There is an info
table and it has relationship to car
table or suv
table.
Itis specified in info.type
field.
So how can I create association on fly based on the type data of the record?
class Info(Base):
item_id = Column(ForeignKey('cars-or-suvs-table.id'))
type = Column(String())
class Car(Base):
- data -
info = relationship('Info', backref="car")
class Suv(Base):
- data -
info = relationship('Info', backref="suv")
Edit: I already have the tables filled with data, so I can not change db schema.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您正在寻找不需要将外键移动到不同表的解决方案,因此您可以尝试以下方法:
我将 Info.car 重命名为 Info._car,因为 ._car 将不可避免地成为伪造的汽车对象,即使 .类型是“suv”。
为了保持简单,我保留了事件侦听器的内容,但是您绝对可以从我的其他答案中调整您需要的部分,以避免事情陷入不一致的状态。
Since you're looking for a solution that doesn't require moving the foreign key to a different table, you can try this approach:
I renamed Info.car to Info._car since ._car will unavoidably be a bogus car object even if .type is 'suv'.
I've left the event listener stuff out to keep it simple, but you can definitely adapt what pieces you need from my other answer to avoid things getting into an inconsistent state.
在 SQL 中,外键必须映射到一个特定的表,因此您需要将外键放在指向“info.id”的“car”或“suv”表中。
对于您所需要的来说,这可能有点过分了,但这里有一种解决方法(假设您实际上希望每辆车只有一个信息):
事件侦听器的复杂性给您带来的是,当您执行以下操作:
或
如果您想自己保持 Info.type、Info.car 和 Info.suv 一致,则可以省略所有事件侦听器函数。
为 CarInfo 和 SuvInfo 提供单独的对象和表也是一个非常合理的选择,并完全避免所有这些复杂性。
In SQL, a foreign key must be mapped to one specific table, so you need to put the foreign key in the 'car' or 'suv' table pointing to 'info.id'.
This is probably overkill for what you need, but here's one way to solve it (assuming you do in fact want each Car to have only one Info):
What the complexity of the event listeners gets you is that the type is automatically managed when you do something like:
or
If you want to keep Info.type, Info.car, and Info.suv consistent yourself, you can omit all the event listener functions.
It would also be a very reasonable option to have separate objects and tables for CarInfo and SuvInfo, and avoid all this complexity altogether.