【问题标题】:Making SQLAlchemy records from a list从列表中制作 SQLAlchemy 记录
【发布时间】:2014-05-02 17:45:29
【问题描述】:

对 Python 很新,对 SQLAlchemy 很新。想知道如何使用for 循环从列表中创建多个 SQLAlchemy 记录。这是我所拥有的非常简化的版本。

class ListItem(Base): 
    __tablename__ = list_items
    id = Column(Integer, primary_key=True)
    item = Column(String(50))

def list_to_ListItem(list_of_things): 
    for thing in list_of_things: 
        listitem = ListItem()
        listitem.item = thing

我还没有运行它,因为实际上我的代码还有很多需要解决的问题,但我的印象是,与其在 list_items 中为每个 thing 创建记录,不如说是在list_of_things 中,这将简单地创建一个分配给listitem 的记录,它将被for 循环的每次迭代覆盖。

那么我该怎么做呢?就像我说的,我对 Python 还很陌生,但我听说过一些我不理解的工厂函数,但至少在名称上,这听起来很有希望解决这个问题。提前致谢!

【问题讨论】:

    标签: python oop python-2.7 for-loop sqlalchemy


    【解决方案1】:

    List comprehension?

    list_items = [ListItem(item=thing) for thing in list_of_things]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多