【问题标题】:SQLAlchemy Session add() return valueSQLAlchemy Session add() 返回值
【发布时间】:2013-10-23 16:33:58
【问题描述】:

使用 sqlalchemy 处理金字塔:

newjob_obj=Job(name=name,job_propery=job_property,sizeX=sizeX,
    sizeY=sizeY,quantity=quantity,timeline=timeline,
    description=description,remarks=remarks,
    client_id=client_id,created_by=created_by,status=status
)
new_job=session.add(newjob_obj)
print('Return newJob value %s\n' % new_job)

这里 new_job 打印为None。 会话的添加函数是否返回对象。请帮忙。

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    在@mark's answer的评论中回答您的问题 - 以便在提交后收到您的“插入的 ID”:

    session.add(newjob_obj)
    session.commit()
    

    你应该刷新插入的对象:

    session.refresh(newjob_obj)
    print newjob_obj.id
    

    希望对您有所帮助..

    【讨论】:

      【解决方案2】:

      这是预期的输出。 add() 不返回值。 The documentation:

      在 Session 中放置一个对象。

      它的状态将在下一次刷新时持久化到数据库中 操作。

      对 add() 的重复调用将被忽略。 add() 的反义词是 删除()。

      The code:

      def add(self, instance, _warn=True):
          """Place an object in the ``Session``.
      
          Its state will be persisted to the database on the next flush
          operation.
      
          Repeated calls to ``add()`` will be ignored. The opposite of ``add()``
          is ``expunge()``.
      
          """
          if _warn and self._warn_on_events:
              self._flush_warning("Session.add()")
      
          try:
              state = attributes.instance_state(instance)
          except exc.NO_STATE:
              raise exc.UnmappedInstanceError(instance)
      
          self._save_or_update_state(state)
      

      add 方法不返回值。当 Python 函数不返回值时,该函数的行为就像它返回 None。如果您想打印作业,您可以打印:

      session.add(newjob_obj)
      print('Return newJob value %s\n' % newjob_obj)
      

      你看,当你 add() 会话对象时,SQLAlchemy 不会真正做任何重要的事情(比如对数据库运行查询)。它将做的只是跟踪对象存在的事实。然后当你做...

      session.commit()
      

      ...您添加的所有对象都被插入到数据库中(除其他外,例如对修改和删除的对象执行 UPDATE 和 DELETE)。

      有关详细信息,请参阅文档中的 using the session chapter

      【讨论】:

      • 感谢 Mark .. session.add(newjob_obj) n 当我按照上面的方法进行操作时,在执行 sesson.commit() 后我无法获得 newjob_obj.id。但是如果我执行 session.flush(),我可以获得 newjob_obj.id。请让我知道如何使用 session.flush() 或 session.commit() 提交
      • 现在很有意义。谢谢!
      【解决方案3】:

      对于SQLite,一旦提交,就可以直接从对象中获取插入的id:

      session.add(newjob_obj)
      session.commit()
      print('Return newJob id %d\n' % newjob_obj.id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-08
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 2018-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多