Python-powered chat apps with Twilio and SendGrid Transcripts
Chapter: Course conclusion and review
Lecture: Review: Inserting data with SQLAlchemy
Login or purchase this course to watch this video and the rest of the course contents.
0:00 Once our databases all set up, we would love to save some data into it. For example, when we get a new order for a user,
0:07 we want to make sure that that user already exists and, if not, create one and then associate the order,
0:12 which we're going to insert into the database with them. So recall I created this handy utility session context.
0:19 SQLAlchemy uses the unit of work session concept, but it doesn't naturally follow with blocks or other language constructs.
0:27 To make that more consistent and automatic in the GitHub Repo, you'll find our session context here, and we say, commit_on_success=True,
0:35 which means if you leave the with block successfully, apply all those changes. If there's an error,
0:39 somehow don't apply the changes, and then we're just going to go do a query for the user, and we're gonna find them by email or phone number.
0:47 So we're gonna use the or_ operator. I would say first to give us the one and only one or give us none If there is no user didn't exist,
0:56 we're going to quick create one, and there's a session.add and then we're going to create an order and we're
1:01 going to say this user, follow their relationship independent order to it and that will both update the user if necessary,
1:07 and insert the order into the database when we leave this with Block because our session finished up sucessfully.