提交会话之前获取插入的密钥 [英] Get inserted key before commit session

查看:155
本文介绍了提交会话之前获取插入的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

父类(db.Model):
id = db.Column(db.Integer,primary_key = True)
$ b $ class Child(db .Model):
id = db.Column(db.Integer,primary_key = True)
parent_id = db.Column(db.Integer,db.ForeignKey('parent.id'))

parent = Parent()
db.session.add(parent)
$ b $ child = Child()
child.parent_id = parent.id
db.session.add(child)

db.session.commit()

我想将 INSERT 插入会话中的表中, parent_id 必须包含在表中。在创建子元素对象的那一刻, parent.id None >

如何才能达到这个目标?

=http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=flush#sqlalchemy.orm.session.Session.flush =noreferrer> flush()刷新对数据库的更改,从而更新主键字段:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ db $。 session.add(parent)
db.session.flush()

在flush()后打印parent.id,父对象将被自动赋值为
#其ID域的键

child = Child()
child.parent_id = parent.id
db.session.add(child)


class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

parent = Parent()
db.session.add(parent)

child = Child()
child.parent_id = parent.id
db.session.add(child)

db.session.commit()

I want to INSERT into both parent and child tables inside a session considering that the parent_id must be included in the child table. In the moment I create the child object, parent.id is None.

How can I achieve that?

解决方案

You could use flush() to flush changes to the database and thus have your primary-key field updated:

parent = Parent()
db.session.add(parent)
db.session.flush()

print parent.id  # after flush(), parent object would be automatically
                 # assigned with a unique primary key to its id field 

child = Child()
child.parent_id = parent.id
db.session.add(child)

这篇关于提交会话之前获取插入的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆