Flask:更新的行数

时间:2018-06-04 21:22:37

标签: python sqlalchemy

如何从Flask中的db.session.commit()获取更新/添加的行数?

如果我尝试:

    for row in csv_data:
        ticket_num = row[0]

        # Generate random UUID token string
        token = uuid.uuid4()

        ticket = Ticket(token, ticket_num, None, None, batch_num)
        db.session.add(ticket)

    num = db.session.commit()
    if num:
        flash(str(num) + ' tickets were uploaded/updated.')

我没有得到任何反馈。

2 个答案:

答案 0 :(得分:2)

会话有属性,您可以检查数据库中会发生什么。会话有new:对于对象,将添加到数据库和dirty:对于对象,将更新:

t1 = Ticket(token, ticket_num, None, None, batch_num)
t2 = Ticket(token, ticket_num, None, None, batch_num)
t3 = Ticket.query.filter_by(token='Something to match').first()
t3.token = 'Something new'
db.session.add_all([t1, t2, t3])

# check for new
>>> db.session.new
IdentitySet([<Ticket (transient 140452313747240)>, <Ticket (transient 140452278620112)>])
# check updates
>>> db.session.dirty
>>>db.session.dirty
IdentitySet([<Ticket 2>])  # 2 is ticket id for me

您可以查看课程长度:len(db.session.new)

请注意,这在提交之前可用,但您将知道已添加和更新了多少项。

答案 1 :(得分:0)

db.session.commit()不会返回任何内容,因此您可能需要尝试跟踪要添加到数据库中的内容的数量,例如:

flash(str(len(csv_data)) + ' tickets were uploaded/updated.')