【问题标题】:Peewee - How to Batch Update and How to Only Update Rows which have been Edited?Peewee - 如何批量更新以及如何仅更新已编辑的行?
【发布时间】:2015-03-04 09:47:09
【问题描述】:

我正在尝试通过为书籍制作笔记应用程序来学习 Peewee 和 Bottle。

模型和关系由Subject -< Book -< Chapter -< Note组成。

note.tpl 页面上,我希望将所有笔记显示在一个表格中,并允许最终用户随意更新任何笔记:

<FORM action="/notes" method="POST">
    <input type="hidden" name="chapter_id" value="{{chapter.id}}"
    <% note_ids = ""
       for note in chapter.notes:
           note_ids += note.id
       end
       note_ids = note_ids[:-1]
    %>
    <input type="hidden" name="note_ids" value="{{note_ids}}" />
    <TABLE>
        <TR><TD>Note Meta</TD><TD>Note</TD></TR>
        % for note in chapter.notes:
            <TR><TD>
                Tag:<input type="text" value="note_tag#{{note.id}}" /><br />
                Pg#:<input type="text" value="page_number#{{note.id}}" /><br />
                </TD>
                <TD> <textarea name="note#{{note.id}}" /><br />
            </TR>
        % end
    </TABLE>
</FORM>

假设我有一个这样的控制器:

@app.route('/notes/, method='POST')
def note_action():
    for i in request.forms.get('note_ids').split(','):
        note = Note(tag=request.forms.get('note_tag#' + i),
        page_number=request.forms.get('page_number#' + i),
        chapter=request.forms.get('chapter_id'))
        note.save()
    chapter = Chapter.select().where(Chapter.id==chapter_id)
    return template('notes', chapter=chapter)

这很糟糕,原因有三个:

1) 它不会进行批量更新,而是一次更新每个音符。如何在 Peewee 中进行批量更新?

2) 它会更新每一个笔记,甚至是用户尚未编辑的笔记。我如何能够确定哪些行已被编辑并仅更新这些行?

很少使用JQuery(或使用它的程度非常有限),我应该如何解决这些问题?

【问题讨论】:

    标签: python bottle peewee batch-updates


    【解决方案1】:

    关于您的第一个问题,迟到总比没有好:Peewee API 没有像 JDBC 的 java.sql.Statement 中那样的 addBatch() 方法。相反,您通过“with”开始事务并做很多工作,Python 处理事务的提交。 Peewee 作者的这篇文章说明了这种方法(不幸的是,该文章末尾关于批量加载数据的链接已损坏):

    https://groups.google.com/forum/#!msg/peewee-orm/YWamQxAYxWU/HTu_wUNLHKUJ

    【讨论】:

    • Peewee 具有bulk insert 功能,要执行批量更新,您可以创建UPDATE 查询。如果您想批量更新或插入,只需使用with db.atomic() 上下文管理器将它们包装在事务中。
    • @coleifer:sql 风格的 addBatch() 和 Python/Peewee 的“with db.atomic()”方法之间有什么有意义的区别吗?我不想传播虚假信息。
    • 我不确定sql-style "addBatch()" 是什么,所以我真的不能说。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多