Flask-Sqlalchemy对象未添加属性

时间:2018-08-09 03:42:06

标签: python flask-sqlalchemy

我正在通过Flask-SQLAlchemy使用ORM。在查询包括审阅者生日的Review对象列表之后,我想更新这些Object的Age属性。在这些对象之间循环并向每个对象添加Age属性时,似乎只保存了最后一个Object的Age。我不确定为什么会这样。有关我的代码和输出,请参见下文。

路线:

# Place Profile Page
@app.route("/placeProfile/<string:id>")
@login_required
def placeProfile(id):
    place = Entity.query.filter_by(id=id).first()
    reviews = Review.query.filter_by(entity_id=id)
    print("first")
    for review in reviews:
        print(review.reviewer_birthday)
        review.reviewer_age = calculate_age(review.reviewer_birthday)
        print(review.reviewer_age)

    print("second")
    for review in reviews:
        print(review.reviewer_birthday)
        print(review.reviewer_age)
    return render_template("entityProfile.html", title='Place Profile', place=place, reviews=reviews)

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

型号:

class Review(db.Model):
    reviewer_age = None
    id = db.Column(db.Integer, primary_key=True)
    reviewer_birthday = db.Column(db.Date)

输出:

first
1993-04-18
25
1988-06-30
30
1993-02-22
25
second
1993-04-18
None
1988-06-30
None
1993-02-22
25

从输出中可以看到,只有最后一个对象的Age值被更新。

0 个答案:

没有答案