python - SQLAlchemy 递归

标签 python recursion sqlalchemy

我学习 Python 很开心,但在尝试将递归函数合并到 SQLAlchemy 中时遇到了一些困难。

本质上,有一个函数可以创建要放入数据库的类的实例。在这个函数中,我获取有关实例是否具有父类(使用自引用邻接表定义)的用户输入。如果是,则再次递归地调用该函数。如果不需要父类,这个函数似乎可以工作,但是每当激活递归元素时,它就会崩溃。

我的代码是这样的:

engine = create_engine('sqlite:///recDB.db')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()

class IngList(Base):
    __tablename__ = "ingList"

    id = Column(Integer, primary_key = True)
    ingredient = Column(String, nullable=False)
    parentIng = Column(Integer, ForeignKey('ingList.id'))
    children = relationship("IngList",backref=backref('parent', remote_side=[id]))

    def __init__(self, ingredient):
        self.ingredient = ingredient

def addIngredient(ingredient):
    global newIngList
    newIng = IngList(ingName) #create new class instance
    parentIng = raw_input("To add parent ingredient, type it.  Otherwise press enter")
    if parentIng != '':
        parentIngObj = addIngredient(parentIng) # Recursion!
        newIng.parentIng = parentIngObj
    newIngList.append(newIng)

if __name__ == '__main__':
    newIngList = []
    ingredient = raw_input("Enter new ingredient")
    addIngredient(ingredient)
    for ing in newIngList
        session.add(ing)
    session.commit()

为了保持可读性,我保持了这个示例的简单性,但如果我遗漏了一些重要信息,请告诉我。

我认为我的问题是类实例在递归时失去了范围,但将全局添加到列表变量似乎并没有解决这个问题。我还认为 session 充当某种缓冲区的事实可以处理任何范围问题。

这和eager loading有关系吗? ?我在文档中看到了这一点,但并没有真正理解它。

我收到的错误是:

Traceback (most recent call last):
  File "C:\workspace\recipes\langProc.py", line 102, in <module>
    session.commit()
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 645, in commit
    self.transaction.commit()
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 313, in commit
    self._prepare_impl()
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 297, in _prepare_impl
    self.session.flush()
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 1547, in flush
    self._flush(objects)
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 1616, in _flush
    flush_context.execute()
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 328, in execute
    rec.execute(self)
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 472, in execute
    uow
  File "c:\Python27\lib\site-packages\sqlalchemy\orm\mapper.py", line 2153, in _save_obj
    execute(statement, params)
  File "c:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1399, in execute
    params)
  File "c:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1532, in _execute_clauseelement
    compiled_sql, distilled_params
  File "c:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1640, in _execute_context
    context)
  File "c:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1633, in _execute_context
    context)
  File "c:\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 330, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 0 
- probably unsupported type.
u'UPDATE "ingList" SET "parentIng"=? WHERE "ingList".id = ?' 
(<assignDB.IngList object at 0x00000000096969E8>, 4)

最佳答案

我认为您有几个错误/拼写错误导致您的代码无法工作。我假设您创建了一个小代码示例来显示该问题,我希望一旦您修复了原始代码中的这些问题,您的问题也将得到解决:

  • 您应该使用 newIng.parent =parentIngObj,而不是 newIng.parentIng =parentIngObj。我相信这应该可以解决问题。
    因此,您必须将父实例分配给关系对象,而不是其键。使用J.F.如果对象已存储在数据库中,但新实例尚未分配id,那么 Sebastian 的建议也可能有效
  • addIngredient(...) 有两个问题:
    • 拼写错误:参数ingredient 应重命名为ingName,反之亦然
    • 更大的问题:addIngredient(...) 不返回任何值,因此实际上您将 None 分配给 parent 端的关系。
      同样,鉴于这只是示例代码,您的实际代码中可能不会出现这些问题。

关于python - SQLAlchemy 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8062157/

相关文章:

包中的递归 S3 调用

c++ - 为什么我的删除节点功能不起作用?

python - Pyramid 、sqlalchemy dbsession

python - 从字符串中拉出部分(python)

python - 正则表达式只捕获重复组的最后一次出现

python - Musixmatch api 响应返回 200 但返回带有 None 值的 json

java - 数独求解器递归

python - 由 gunicorn 运行的 Flask 应用程序在一段时间后被挂起

Flask-WTForms 和 SQLAalchemy SelectField 的关系

python - MySQL服务器消失了