#100DaysOfCode in Python Transcripts
Chapter: Days 91-93: Database access with SQLAlchemy
Lecture: Your turn: Day 2

Login or purchase this course to watch this video and the rest of the course contents.
0:00 On Day 2, you're going to focus on building out the database models and the database structure.
0:06 So, recall from the presentation, that what you need to do is use some kind of base class that comes from
0:13 SQLAlchemy, and have all of your models derive from that. So, here's the example we had for our move, in our game,
0:19 and it derived from model base, we controlled the table, by putting table name in there. This is optional, but I like to do it.
0:27 And then we just defined all the columns. Has integers, or has date times or strings, and then be sure to give it a primary key,
0:34 and auto-increment if that's an integer, nice and easy. And then you're going to need to actually go and create
0:41 the database, using your base model there. And create a session factory for use later. Alright, so if you run this code, already,
0:49 you should actually have some kind of database file, and whatever you call it here, you'll have down here. And then, you can either look at it,
0:56 if you're using Pycharm Pro, in Pycharm Pro, or you can use a DB Browser for SQLite. Either way, this is going to get your database structure
1:05 all up and running. Final warning, or final note here: Beware, you cannot modify existing tables, so for example,
1:12 this move, if I decided I also wanted some other value here, like the opponent's role, or you know, whatever,
1:20 if I want to change this, at all, once I run this bit here, it's fixed, can't change it. SQLAlchemy will just ignore it, and it probably will crash
1:30 when you try to work with it, who knows. So, if you want to do that, you need to use what's called
1:33 migrations, or for this little example, the easiest way would be to just delete the database file, and start over and it will create it, new.
1:40 But in production, migrations, or some kind of database script to do the change, is what's required.


Talk Python's Mastodon Michael Kennedy's Mastodon