【发布时间】:2017-09-29 00:29:36
【问题描述】:
我正在尝试根据我检索的数据动态创建数据库表和列。 我检索数据库列表、列名称和属性列表,例如列类型、primary_key / 唯一、可为空以及其他元数据。 我正在尝试使用这些信息来动态创建表格,并且一直在使用论坛帖子来更好地了解如何实现这一点。所以我想根据我检索到的信息创建表 - 数据库和列信息(列名和列类型、主键和可为空的信息。检索到的信息可能每天或每周更改。 论坛帖子 #1 - Sqlalchemy dynamically create table and mapped class
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()
有一个错误信息:
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'
任何想法我做错了什么?
【问题讨论】:
-
请包括完整的回溯,包括行号等。
-
我建议您从tutorial开始使用 SQLAlchemy
-
@AzatIbrakov 感谢您提供的信息,您的解决方案对我有用。我已经断断续续地阅读教程有一段时间了,可能我需要在更广泛的基础上获得更多知识。
-
这意味着您将
list对象ctype作为参数传递给Column初始化程序的type_参数,但它应该是TypeEngine子类之一(如String和@ 987654332@) -
标签: python sqlalchemy