SQLAlchemy Session add()返回值

2024-05-17 14:44:45 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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)

新的作业正在打印为None。 会话的add函数是否返回object。请帮忙。


Tags: nameclientidobjbystatusjobdescription
1条回答
网友
1楼 · 发布于 2024-05-17 14:44:45

在@mark的回复评论中回答您的问题-为了在提交后收到您的“插入的ID”:

session.add(newjob_obj)
session.commit()

应使用以下命令刷新插入的对象:

session.refresh(newjob_obj)
print newjob_obj.id

希望能帮上忙。。

网友
2楼 · 发布于 2024-05-17 14:44:45

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

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().

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()

…您添加的所有对象都将插入到数据库中(其中包括对已修改和已删除的对象执行更新和删除操作)。

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

相关问题 更多 >