Posts

Showing posts with the label sqlalchemy

SQLAlchemy Object Lifecycle

Image
 SQLAlchemy Object Lifecycle Recall We can insert new records into the database using SQLAlchemy by running. - person = Person(name='Amr') - db.session.add(person) - db.session.commit() which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit(). db.session: It isn't until we execute db.session() that we commit anything to the database. Every time we want to interact with the database we start a connection and end a connection when all of the interactions are done. Within that interaction session, We wound up creating transactions that we commit to the database every time that we want to commit work to the database.  So an important thing to keep in mind: - Proposed database changes are not immediately committed to the database once they're defined.  - Changes go through stages in order to provide the ability to "undo" a mistake.  - before committing it to a database. There are 4 st...

SQLAlchemy Model.query cheat-sheet

Image
SQLAlchemy  Model  query-cheat-sheet Query Methods Here are some useful query methods to get to know.  - Select records all() MyModel.query.all() Fetches all records from a table. Returns list of objects. first() MyModel.query.first() Fetches just the first result. Returns object or None. - Filtering filter_by() MyModel.query.filter_by(attr='some value') Similar to SELECT * from ... WHERE filter() Examples: MyModel.query.filter(MyOtherModel.some_attr='some value') OrderItem.query.filter(Product.id=3) Similar to filter_by , but instead, you specify attributes on a given Model.-- -- equals: query.filter(User.name == 'ed') -- not equals: query.filter(User.name != 'ed') LIKE : query.filter(User.name.like('%ed%')) ILIKE (case-insensitive LIKE): query.filter(User.name.ilike('%ed%')) IN: query.filter(User.name.in_(['ed', 'wendy', 'jack'])) NOT IN: query.filter(~User.name.in_(['ed', 'wendy', 'jack...