使用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
。
添加会话功能返回对象与否。请帮忙。
答案 0 :(得分:13)
在@ mark的回答评论中回答你的问题 - 为了在提交后收到你的“插入ID”:
session.add(newjob_obj)
session.commit()
您应该使用以下内容刷新插入的对象:
session.refresh(newjob_obj)
print newjob_obj.id
希望有所帮助......
答案 1 :(得分:6)
这是预期的输出。 add()
不会返回值。 The documentation:
在会话中放置一个对象。
它的状态将在下次刷新时持久保存到数据库 操作
将忽略对add()的重复调用。与add()相反的是 抹去()。
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。
答案 2 :(得分:-1)
对于SQLite,一旦提交,就可以直接从对象获取插入的ID:
session.add(newjob_obj)
session.commit()
print('Return newJob id %d\n' % newjob_obj.id)