在flask中获取最后插入的id的问题

时间:2014-04-01 15:53:33

标签: python flask flask-sqlalchemy

我在flask中插入数据,但我无法获取最后插入的id

mdeals = Deals(
                merchand_id = session['userid'],
                deal_name=request.form['dealname'],
                deal_desc=request.form['dealdescription'],
                .
                            .
                            .
                )
        mdeals.save()

我的模特是:

class Deals(db.Model):
    __tablename__ = 'deals'
    dealid = db.Column('id', Integer, primary_key=False)
    deal_name = db.Column('deal_name', String(50), unique=False)
    deal_desc = db.Column(db.Text, unique=False)
    deal_price = db.Column('deal_price', String(50), unique=False)
    deal_savings = db.Column(db.Float, unique=False)
    deal_qty = db.Column(db.Integer(), unique=False)
    start_time = db.Column(db.DateTime, unique=False)
    end_time = db.Column(db.DateTime, unique=False)
    created_on = db.Column(db.DateTime, unique=False)
    updated_on = db.Column(db.DateTime, unique=False)
    merchand_id = db.Column(db.Integer(), db.ForeignKey(Merchant.id))
    merchand = db.relationship(Merchant , backref='posts')
    def __init__(self, deal_name=None,deal_price=None ):
        self.deal_name = deal_name
        self.deal_desc = deal_price

但是,当我尝试抓取mdeals.id时,它会给我None,如果我尝试抓取mdeals.dealid,那么它会显示错误AttributeError: 'Deals' object has no attribute 'dealid',

我很困惑,我怎么能得到最后一个插入的id?

由于

1 个答案:

答案 0 :(得分:1)

from yourapp import Deals
de = Deals(merchand_id = session['userid'],
            deal_name=request.form['dealname'],
            deal_desc=request.form['dealdescription']...)
db.session.add(de)
db.session.commit()

之后你可以看到id

print de.dealid