我正在尝试根据我检索的数据动态创建数据库表和列.我检索数据库列表,列名和列属性列表,如列类型,primary_key/unique,nullable以及其他元数据.我正在尝试使用此信息动态创建表,并一直使用论坛帖子来更好地了解如何实现这一点.所以我想根据我检索的信息创建表 - 数据库和列信息(colnames和列类型,主键和可空信息.检索到的信息可以每天或每周更改.论坛帖子#1 - Sqlalchemy动态创建表格和映射类
postgresql_db = engine(...)
post_meta = sql.MetaData(bind=postgresql_db.engine)
post_meta.reflect(schema='customers')
connection = postgresql_db.engine.connect()
col_names = ['id', 'fname', 'lname', 'age']
ctype = ['Integer', 'String', 'String', 'Integer']
pk = ['True', 'False', 'False', 'False']
nulls = ['No', 'No', 'No', 'No']
class test(object):
test = Table('customers', post_meta,
*(Column(col, ctype, primary_key=pk, nullable=nulls)
for col, ctype, pk, nulls in zip(col_names, ctype, pk, nulls))
test.create()
Run Code Online (Sandbox Code Playgroud)
有一条错误消息:
AttributeError: 'list' object has no attribute _set_parent_with_dispatch
似乎无法确定此错误的确切含义.
追溯:
Traceback (most recent call last):
File "C:/Users/xxx/db.py", line 247, in <module>
main()
File "C:/Users/xxx/db.py", line 168, in main
for col, ctype, pk, nulls in zip(col_names, ctype, pk, nulls)
File "C:/Users/xxx/apidb.py", line 168, in <genexpr>
for col, ctype, pk, nulls in zip(col_names, ctype, pk, nulls)
File "C:\Python27\lib\site-packages\sqlalchemy\sql\schema.py", line 1234, in __init__
self._init_items(*args)
File "C:\Python27\lib\site-packages\sqlalchemy\sql\schema.py", line 79, in _init_items
item._set_parent_with_dispatch(self)
AttributeError: 'list' object has no attribute '_set_parent_with_dispatch'
Run Code Online (Sandbox Code Playgroud)
我有什么想法我做错了吗?
这里有很多不正确的事情.
nullable在参数Column初始化应该有类型bool,但是你想传递一个str对象nulls,同样的事情pk和primary_key参数.
此外,您要覆盖的名字ctype,pk,nulls在理解,这是不正确的,并提出给予例外.您应该重命名从zip理解中生成的对象.
SQLAlchemy不会识别字符串'Integer','String'它们不是有效Column类型.
如果要反映特定的表调用'customers',应该使用参数only,而不是schema,它应该是list名称.
你也不需要上课test.
你的代码看起来像
from sqlalchemy import MetaData, Table, Column, Integer, String
postgresql_db = engine(...)
post_meta = MetaData(bind=postgresql_db.engine)
post_meta.reflect(only=['customers'])
connection = postgresql_db.engine.connect()
columns_names = ['id', 'fname', 'lname', 'age']
columns_types = [Integer, String, String, Integer]
primary_key_flags = [True, False, False, False]
nullable_flags = [False, False, False, False]
test = Table('customers', post_meta,
*(Column(column_name, column_type,
primary_key=primary_key_flag,
nullable=nullable_flag)
for column_name,
column_type,
primary_key_flag,
nullable_flag in zip(columns_names,
columns_types,
primary_key_flags,
nullable_flags)))
test.create()
Run Code Online (Sandbox Code Playgroud)
最后,如果你这样做post_meta.reflect(only=['customers'])并且它有效,那么可以简单地获得给定的表
test = post_meta.tables['customers']
Run Code Online (Sandbox Code Playgroud)
没有从头开始构建.
| 归档时间: |
|
| 查看次数: |
2119 次 |
| 最近记录: |