获取Flask中一对一关系的“insert_id”,SqlAlchemy

时间:2015-06-08 01:04:18

标签: flask flask-sqlalchemy

我正在尝试通过sqlalchemy插入一个新行。父表(里程碑)有一个名为Funding的子表。两个表通过名为milestone_id的列共享关系。这是一对一的关系。

我查了一下,但在插入Funding表中的新行时,我无法弄清楚如何引用milestone_id。父ID是自动增量。我正在使用Flask和SqlAlchemy。

模型:

 class Milestone(db.Model):
    __tablename__ = "**************"

   milestone_id = db.Column(db.Integer, primary_key=True)
   company_id = db.Column(db.Integer, db.ForeignKey('stlines_startups.company_id'))
   milestone_date = db.Column(db.Integer)
   snapshots = db.relationship('Snapshot', uselist=False, primaryjoin='Milestone.milestone_id==Snapshot.milestone_id', backref='milestone')
   fundraising = db.relationship('Funding', uselist=False, primaryjoin='Milestone.milestone_id==Funding.milestone_id', backref='milestone')

   def __init__(self, milestone_id, company_id, milestone_date, snapshots = [], fundraising = []):
    self.milestone_id = milestone_id
    self.company_id = company_id
    self.milestone_date = milestone_date
    self.snapshots = snapshots
    self.fundraising = fundraising

class Funding(db.Model):
    __tablename__ = "**************************"

   funding_id = db.Column(db.Integer, primary_key=True)
   funding_type = db.Column(db.Text)
   funding_message = db.Column(db.Text)
   funding_amount = db.Column(db.Integer)
   milestone_source = db.Column(db.Text)
   company_id = db.Column(db.Integer, db.ForeignKey('stlines_milestones.company_id'))
   milestone_id = db.Column(db.Integer, db.ForeignKey('stlines_milestones.milestone_id'))
   user_id = db.Column(db.Integer)
   funding_timestamp = db.Column(db.Integer)

def __init__(self, funding_id, funding_type, funding_message, funding_amount, milestone_source, milestone_id, company_id, user_id, funding_timestamp):
    self.funding_id = funding_id
    self.funding_type = funding_type
    self.funding_message = funding_message
    self.funding_amount = funding_amount
    self.milestone_source = milestone_source
    self.milestone_id = milestone_id
    self.company_id = company_id
    self.user_id = user_id
    self.funding_timestamp = funding_timestamp

炼金术查询:

@app.route('/_add_funding')
def add_funding():
    funding_type = request.args.get('funding_stage', '', type=str)
    funding_message = request.args.get('funding_message', '', type=str)
    funding_amount = request.args.get('funding_amount', 0, type=int)
    milestone_source = request.args.get('milestone_source', '', type=str)
    milestone_date = request.args.get('milestone_date', '', type=str)
    company_id = request.args.get('company_id', '', type=int)

    milestone_date_final = datetime.datetime.strptime(milestone_date, '%B %d, %Y')

    ''' In this line, I try to reference milestone_id with new_milestone.milestone_id, but nothing shows up in the database '''
    new_funding = Funding('', funding_type=funding_type, funding_message=funding_message, funding_amount=funding_amount, milestone_source=milestone_source, company_id=company_id, milestone_id=new_milestone.milestone_id, user_id='1', funding_timestamp=milestone_date_final)
    new_milestone = Milestone('', company_id=company_id, milestone_date=milestone_date_final, snapshots=None, fundraising=new_funding)
    db.session.add(new_milestone)
    output = new_milestone.milestone_id
    db.session.commit()

    return jsonify(result=output)

在资金表中插入资金信息时,如何告诉SqlAlchemy使用里程碑表中自动生成的milestone_id?这些是两个单独的查询吗?

更新:

我接受了ThiefMaster关于使用flush函数的建议,但我仍然收到错误: UnboundLocalError:在赋值之前引用的局部变量'new_milestone'

这是更新后的代码:

@app.route('/_add_funding')
def add_funding():
    funding_type = request.args.get('funding_stage', '', type=str)
    funding_message = request.args.get('funding_message', '', type=str)
    funding_amount = request.args.get('funding_amount', 0, type=int)
    milestone_source = request.args.get('milestone_source', '', type=str)
    milestone_date = request.args.get('milestone_date', '', type=str)
    company_id = request.args.get('company_id', '', type=int)

    milestone_date_final = datetime.datetime.strptime(milestone_date, '%B %d, %Y')
    ''' In this line, I try to reference milestone_id with new_milestone.milestone_id, but nothing shows up in the database '''
    new_funding = Funding('', funding_type=funding_type, funding_message=funding_message, funding_amount=funding_amount, milestone_source=milestone_source, company_id=company_id, milestone_id=new_milestone.milestone_id, user_id='1', funding_timestamp=milestone_date_final)
    new_milestone = Milestone('', company_id=company_id, milestone_date=milestone_date_final, snapshots=None, fundraising=new_funding)
    db.session.add(new_milestone)
    db.session.commit()
    db.session.flush()
    output = new_milestone.milestone_id

    return jsonify(result=output)

任何想法?

2 个答案:

答案 0 :(得分:0)

db.session.flush()来电后添​​加db.session.add(..)。这将导致INSERT被发送到数据库,之后您将获得ID。

答案 1 :(得分:0)

我找不到确切的解决方案。如果有人想知道,我最终通过直接执行SQL来解决它。它并不理想,但它现在已经完成了工作。我最后一次插入行,这是下面的代码:

@app.route('/_add_funding')
def add_funding():
    funding_type = request.args.get('funding_stage', '', type=str)
    funding_message = request.args.get('funding_message', '', type=str)
    funding_amount = request.args.get('funding_amount', 0, type=int)
    milestone_source = request.args.get('milestone_source', '', type=str)
    milestone_date = request.args.get('milestone_date', '', type=str)
    company_id = request.args.get('company_id', '', type=int)

    milestone_date_final =  time.mktime(datetime.datetime.strptime(milestone_date, '%B %d, %Y').timetuple())

    sql = "INSERT INTO ******** (`milestone_id`,`company_id`, `milestone_date`) VALUES ('','{}','{}')".format(company_id, milestone_date_final)
    result = db.engine.execute(sql)

    milestone_id = result.lastrowid 

    sql = "INSERT INTO ****** (`funding_id`,`funding_type`, `funding_message`, `funding_amount`, `milestone_source`, `company_id`, `milestone_id`, `user_id`, `funding_timestamp`) VALUES ('','{}','{}','{}','{}','{}','{}','1', '{}')".format(funding_type, funding_message, funding_amount, milestone_source, company_id, milestone_id, milestone_date_final)
    result = db.engine.execute(sql)

    output = result.lastrowid
    return jsonify(result=output)