如何动态创建 SQLAlchemy 列

发布于 2024-10-11 22:52:27 字数 1129 浏览 6 评论 0原文

我有一个 csv 文件,第一行作为字段,其余行作为数据。我想用这个文件创建一个表。由于字段很长并且可能会有所不同,因此我想动态创建它。 经过几次尝试和搜索,我想我也许可以从工厂生成一个类,然后将属性分配给新类可以生成动态列。但它失败了。根据这个错误,我尝试了一些其他方法,但都失败了。请帮忙。我正在考虑这样的想法是否可行。

Reader = csv.reader(open('Book1.csv', 'rb'), delimiter=',', quotechar='|')
TableItem = Reader.next()[0:]
def Factory(*args, **kwargs):
    args=args[0]
    def init(self, *iargs, **ikwargs):
        #setattr(self,__tablename__,ikwargs[__tablename__])
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "myFactory")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init})

LIS=Factory(TableItem)
class newLIS(LIS,Base):
    __tablename__='testonly'
    pass
mytest=[]
for row in Reader:
    mytest.append(newLIS(row))

错误是这样的:

sqlalchemy.exc.ArgumentError: Mapper Mapper|newLIS|testonly could not assemble
any primary key columns for mapped table 'testonly'

I have a csv file with first line as fields and remaining lines as data. With this file I would like to create a table. Since the fields are quite long and may vary, I want to dynamically create it.
After several tries and searches, I figured I could maybe generate a Class from factory and then assign the attributes to the new class could generate dynamic columns. But it fails. And based on the error, I tried some other methods, all failed. Please help. I'm considering whether it's doable for such an idea.

Reader = csv.reader(open('Book1.csv', 'rb'), delimiter=',', quotechar='|')
TableItem = Reader.next()[0:]
def Factory(*args, **kwargs):
    args=args[0]
    def init(self, *iargs, **ikwargs):
        #setattr(self,__tablename__,ikwargs[__tablename__])
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "myFactory")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init})

LIS=Factory(TableItem)
class newLIS(LIS,Base):
    __tablename__='testonly'
    pass
mytest=[]
for row in Reader:
    mytest.append(newLIS(row))

The error is like:

sqlalchemy.exc.ArgumentError: Mapper Mapper|newLIS|testonly could not assemble
any primary key columns for mapped table 'testonly'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖兔^ω^ 2024-10-18 22:52:27

我是相关答案的作者:

sqlalchemy 动态映射

我有这个答案另一个问题,我认为更相关 - 它甚至可能是重复的:

使用脚本语言的动态数据库

如您所见,要创建它,您需要创建一个表对象并将其映射到您的类。另外,sqlalchemy 中的映射类需要表上的主键,因此您必须添加一个。除此之外你还有其他问题吗?如果是这样,您可以粘贴您更新的代码吗?

I'm the author of the related answer:

sqlalchemy dynamic mapping

I have this answer to another question, which I think is even more related - it could even be a duplicate:

Database on the fly with scripting languages

As you can see, to make it you need to create a table object and map it against your class. Also, mapped classes in sqlalchemy need a primary key on the table, so you have to add one. Are you having any other problem besides that? If so, can you paste your updated code?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文