theQman
theQman

Reputation: 1780

How to update using SQLAlchemy and session?

When I want to add a row to my MyProducts table I do:

p = models.MyProducts(code="123456")
db.session.add(p)
db.session.commit()

Inside models.py I have:

class MyProducts(db.Model):
    id = db.Column(db.Integer, primary_key = True, autoincrement=True)
    code = db.Column(db.Integer)
    quantity = db.Column(db.Integer, default=1)
    comment = db.Column(db.String(99999), default="")
    pricepaid = db.Column(db.Float(264), default="0.0")

How do I go about updating my the row that has a code of "123456" ? I have tried

updater = models.MyProducts.query.filter_by(code="123456").update({'comment':"greeeeat product"})
db.session.add(updater)
db.session.commit()

but this doesn't work.

Upvotes: 2

Views: 3429

Answers (1)

van
van

Reputation: 76962

Assuming it is just one product:

my_product = models.MyProducts.query.filter_by(code=123456).first()  # @note: code is Integer, not a String, right?
if my_product:
    my_product.comment = "greeeeat product"
    db.session.add(my_product)
    db.session.commit()

Upvotes: 7

Related Questions