gpt4 book ai didi

Python sqlalchemy 映射没有主键的表

转载 作者:行者123 更新时间:2023-12-01 00:46:50 25 4
gpt4 key购买 nike

我有一个第三方数据库,我尝试使用 sqlalchemy 和 python 进行映射。数据库中的表不使用主键。我喜欢避免自己定义表,因为表有很多列。所以我写了下面的代码

在 sqlalchemy 的文档中找到以下映射器参数。

class MyTable(Base):
__tablename__ = 'MyTable'
__mapper_args__ = {'primary_key':[some_table_with_no_pk.c.uid, some_table_with_no_pk.c.bar]
.....
}

但对我来说,不清楚如何添加正确的命名,例如

{'primary_key':['MyTable', 'MyColumnInTable'] }
or
{'primary_key':'[MyTable, MyColumnInTable]' }

不起作用。我该如何映射这个?感谢您的帮助

最佳答案

正如您可以阅读的那样 here :

primary_key – A list of Column objects which define the primary key to be used against this mapper’s selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.

所以你可以这样做:

class MyTable(Base):
__tablename__ = "my-table"

field1 = Column(String(10))
field2 = Column(String(10))

__mapper_args__ = {
"primary_key":[field1, field2]
}

关于Python sqlalchemy 映射没有主键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com