使用 sqlalchemy 将 multipledict 中的数据插入多行

发布于 2024-11-29 18:31:54 字数 611 浏览 2 评论 0原文

假设我有一个包含以下列的表:

id, title, description

我有一个包含多个同名输入字段的表单。例如:

<input type='text' name='title' value = 'A title' />
<input type='text' name='title' value = 'Another title' /> etc...

我从 POST 请求中获取以下多重字典。

([('title', 'A title'), ('description', 'A description'), 
('title', 'Another title'), ('description', 'Another description'), 
('title', 'One more title'), ('description', 'One more description')])

我的问题是,从上面的数据中,我如何将每一行数据与上面的多字典分开,并使用 SQLAlchemy 执行“INSERT INTO”,以便将数据插入到表中的多行中。

谢谢。

Assuming I have a table with the following columns:

id, title, description

I have a form with multiple input fields with the same names. E.g.:

<input type='text' name='title' value = 'A title' />
<input type='text' name='title' value = 'Another title' /> etc...

I get the following multidict from the POST request.

([('title', 'A title'), ('description', 'A description'), 
('title', 'Another title'), ('description', 'Another description'), 
('title', 'One more title'), ('description', 'One more description')])

My question is, from the data above how would I seperate each row of data from the multidict above and do an 'INSERT INTO' using SQLAlchemy, so data is inserted into multiple rows in the table.

Thanks.

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

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

发布评论

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

评论(2

凹づ凸ル 2024-12-06 18:31:54

以下(独立的工作示例)代码应该可以让您了解:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True,)
metadata = MetaData()

mytable = Table('mytable', metadata,
    Column('id', Integer, primary_key=True),
    Column('title', String(50)),
    Column('description', String(50)),
)

class MyObject(object):
    # 1. define keywork based constructor (or do this in the part 2.)
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

mapper(MyObject, mytable)
metadata.create_all(engine)

session = sessionmaker(bind=engine, autoflush=False)()

input = ([('title', 'A title'), ('description', 'A description'), 
('title', 'Another title'), ('description', 'Another description'), 
('title', 'One more title'), ('description', 'One more description')])

# 2. add data to the session, then commit
while input:
    values = dict((input.pop(0), input.pop(0)))
    obj = MyObject(**values)
    session.add(obj)
session.commit()

Following (self-contained working sample) code should give you the idea:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True,)
metadata = MetaData()

mytable = Table('mytable', metadata,
    Column('id', Integer, primary_key=True),
    Column('title', String(50)),
    Column('description', String(50)),
)

class MyObject(object):
    # 1. define keywork based constructor (or do this in the part 2.)
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

mapper(MyObject, mytable)
metadata.create_all(engine)

session = sessionmaker(bind=engine, autoflush=False)()

input = ([('title', 'A title'), ('description', 'A description'), 
('title', 'Another title'), ('description', 'Another description'), 
('title', 'One more title'), ('description', 'One more description')])

# 2. add data to the session, then commit
while input:
    values = dict((input.pop(0), input.pop(0)))
    obj = MyObject(**values)
    session.add(obj)
session.commit()
木落 2024-12-06 18:31:54

我使用 multidict.getall()zip 在我的代码中实现相同的目的:

...
input = ([('title', 'A title'), ('description', 'A description'), 
          ('title', 'Another title'), ('description', 'Another description'), 
          ('title', 'One more title'), ('description', 'One more description')])

titles = input.getall('title')
descriptions = input.getall('description')
for title, description in zip(titles, descriptions):
    obj = MyObject(title, description)
    session.add(obj)
...

它似乎更清晰一些,但我不知道其他优点/缺点。

I use multidict.getall() and zip to achieve the same in my code:

...
input = ([('title', 'A title'), ('description', 'A description'), 
          ('title', 'Another title'), ('description', 'Another description'), 
          ('title', 'One more title'), ('description', 'One more description')])

titles = input.getall('title')
descriptions = input.getall('description')
for title, description in zip(titles, descriptions):
    obj = MyObject(title, description)
    session.add(obj)
...

It seems a bit more clear but I don't know about other advantages/disadvantages.

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