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,
0:01 we would love to save some data into it.
0:03 For example, when we get a new order for a user,
0:06 we want to make sure that that user already exists and,
0:08 if not, create one and then associate the order,
0:11 which we're going to insert into the database with them.
0:14 So recall I created this handy utility session context.
0:18 SQLAlchemy uses the unit of work session concept,
0:22 but it doesn't naturally follow with blocks or other language constructs.
0:26 To make that more consistent and automatic in the GitHub Repo,
0:30 you'll find our session context here,
0:32 and we say, commit_on_success=True,
0:34 which means if you leave the with block successfully,
0:36 apply all those changes. If there's an error,
0:38 somehow don't apply the changes, and then we're just going to go do a query
0:42 for the user, and we're gonna find them by email or phone number.
0:46 So we're gonna use the or_ operator.
0:48 I would say first to give us the one and only one or give us none
0:52 If there is no user didn't exist,
0:55 we're going to quick create one,
0:56 and there's a session.add and then we're going to create an order and we're
1:00 going to say this user, follow their relationship independent order to it and that will
1:04 both update the user if necessary,
1:06 and insert the order into the database when we leave this with Block because our session finished up sucessfully.