2022-06-28 | Django | PostgreSQL Crash Course for Django
PostgreSQL基础教程:Django开发者快速入门
标签
媒体详情
- 上传日期
- 2025-06-08 00:08
- 来源
- https://www.youtube.com/watch?v=2zRHeUNjsig
- 处理状态
- 已完成
- 转录状态
- 已完成
- Latest LLM Model
- gemini-2.5-pro-preview-06-05
转录
speaker 1: Hi, everyone, and welcome to this chapter of the free full stack course. In this chapter, we're going to focus on some of the basics of postgres sl. Now we need to know that when we get started with the back end development using Jango, Jango abstracts away quite a lot of database management for us. That means really that you don't have to work directly actually with postgres or any other database for that matter, even if you are using sql life, for instance, or mysl when you're with Jango. When you're using Jango, as you'll soon see when we get started with Jango actually in the later chapters, you don't go ahead and write, for instance, direct sql queries and whether it's postgres or sql ite or whatever. So it is important to understand that we don't need to go ahead and learn everything about postgres, for instance, but we should actually learn just a little bit so that we understand at least how postgreworks under the hood and also to get an understanding of how it relates to sql, the standard sl as well. There are some commands that are specific to postgrethat you can't take, and they're basically not portable commands that you can take to MySQL. But there also but postgres also is a sql database, so it allows you to add sql commands in the postgreshell, for instance, to interact with it. So just keep it in mind. We're not going to go in very much detail about postgres, but just some some of the basics in this chapter. At least we get a good understanding of how postgres works. Okay. So let me do some screen reshuffling here before we get started with getting connection information in postgreso. I'm going to go ahead and make the screen a little bit bigger in here and shift to a terminal window. If you follow the chapters chronologically, or at least follow the chapter from the previous chapters for installing postgres, you should now have a user on your computer called full, full stack course. And even if you don't create that, the local user on your computer, actually the local user was only really for unix based operating system, so maos and also Linux. But if you're on windows, you don't have a special user really on your computer for full side course. But what we at least have is a full side course role in postgreor, a user called full stcourse in postgreand also, we should have a database called full stack course. If you follow the chapters from before this current chapter basically. So let's go ahead and go into psql at this prompt. And then I'm going to say I'm going to use the user post. Actually, I'm going to use the user full stack course in here. Okay, so now we're at the full stack course database. So in order to get the connection information you can Press, you can type back flash c. As you can see this is connected to which database and as which user? You can also say con info which gives you some information such as the port on which you are connected. So you can see in here con info gives you some more information then backslash c. So that's also quite useful sometimes because later when we start with Jango, you also need to know which port you're connected to, and that is something that you will also need to configure. The default port for postgres, as you can see in here, is 5432. So unless you've configured postgres at a different port upon the installation, then you don't have to worry about that. It's usually 5432. But when we later in this course go and deploy, for instance, our Jango application to a service such as Google's cloud system, then the ports might be different. And that's something that we always have to take into consideration. So in order to see the port, you can also issue the command con info, not to get only the connection information, but also to see the port. Okay. So the other useful command in postgrel that you can issue, as you can see, is the backslash du. And I can see I've increased the size of the font so much that it's almost impossible to read this information. So let me just change the size in here and let me see if I can issue the same command again in here, ahdu. And if I decrease the size just a little bit more, I think then we can see the information a little bit better, as you can see in here. So by issuing the backslash du command, you can see all the users or all the roles as postgrecalls them. So they're not really called users, although when you log into postgreyou're, actually using the dash upperku as a user to choose that role. But inside postgrewhen, you're inside postgrethese users are called roles basically. Okay, so here you can see with the backslash du command list of all the roles available in the system and also what attributes they have, meaning what permissions that they have here as a super user can and this user can also create roles and also can create databases and also there are other users such as the postgres default user that has more access to the entire system then the role that we've created. But when you create new roles, you can also assign new attributes to them or assign attributes to oner and also you can manipulate those attributes later. This is something that we're not gonna to play with though right now. It's not necessary for this chapter or this course at the moment, but just keep that in mind that there are roles and then there are attributes which is their permissions. Okay, now if you want to see also the history of all the commands that you've issued in postgreterminal, so such as for instance you've issued a command and you just don't remember what it was you can issue the backslash s command in here. You can see that again, I can see a list of commands that I've issued from before. Okay, so that's also quite a handy command. If you're if you've forgotten a command that you've issued before and just want to go back to it, that's pretty nice. Now when you're in the postgressials shelling here, you may be interested in finding all the available databases because this is as a database management system as well, postgres. So the core of it is really data and databases and tables and views and functions, of course. So if you want na see a list of available databases, then you can issue the backslash l command or lists. So let me increase the size zing here a little bit. So let's just say backslash l in here. Actually, the size zes again is too big. So let's see backslash l in here. And you can see in here I can see a list of available databases. So here's a full slack course, databasas a postgreand. Then there's some templates and also there's my other users database. So it's pretty nice command. It's very useful, backslash l, to get the list of available databases in the system. Okay. Now if you want to switch between various databases, like if you issue the backs I see to see your connection information, right now we're connected to the full stack course database. But if you want to switch to another database, you can basically use the backslash c command, but you specify the database you want to connect to. So let's get a list of all the databases in here. And let's just say that I want to connect to the post gredatabase in here. So I say backslic post, and it says that I am the full stack course user. And now I'm connected to the postgres database and I can go back to my full stack course database like this with the backslash c command again. And then I can see, say, backslash c to get the connection information and also backslash l to get the available databases in the system. Okay, now there's lots of these backslash commands in postgres. And then if you want na get a list of them and some help about what they actually do, you can issue the backslash question mark command ding here. And I will tell you the basics of some of these commands and what you can do with them. We're not going to go through all of these because postgres has a lot of postgres specific commands. I'm just going to provide you with some of the most important commands in this chapter so you at least know how to test the waters. Okay. Now if you want to quit this shell for postgreyou, can either type let actually bring the label in here. So if you want to quit your shell, you can either type quit in here or you do the postgresway by doing backslash q and that quits the postgresh shell for you. So if you go back, you can say backslash q and then you can always go back with psql and you can also type quits. I've seen quit also work. So but I prefer backslash qbecause of all the backslash commands versus the post gres command basically. Okay, so let's kind of do postgres again. All right. Now if we're curious about the version of postgres that you're running at the moment, you can use a select commanding here and select is a sql command and version is a function in here. So you say select version and then you can see your postgreversion if you're if you're curious about that. This is kind of important because sometimes when you're asking for help online, you may need to provide this information to whoever's trying to help you. So that person says, okay, which version of postgres are you using? And then you can use this command that you saw in here, a select version, which is a function. Okay? So that's also a good command to remember. Now if you've issued a command and then you want to issue the same command again, there are two ways of doing that. One is just to Press the up arrow on your keyboard to go to that previous command, or you can just say backslash g. So if I say in here, select ective version, for instance, this is, this is the command that I issued previously. If I wanto go back to it, I can either Press the up arrow, which goes back to it, or I can say backslash g, which basically issues that command. Again, you can see it issuthat command. All right. So backslash g is also useful if you want to reissue a command that you just issued. And it's kind of useful for me at least, it's useful when I'm trying to insert some data into a table. For instance, if I've done and insert into a table for a row, and I want to insert it again and again and again, I can just say backslash g, backslash g, backsh g, which reinserts the same data again into the table. Okay, okay. Now that we're now that we've come to this point also, we learn about some of the basics of the backslash commands and getting lists of databases. For instance, you may also be curious about actually working with tables. So the databases and tables are kind of like the basics of sql, you could say. And then you get into views and functions and etcec. But there are many things you can do with databases as well, for instance, in postgres, such as creating databases. And the command for creating a database in postgres, you can see, is very similar to basically any other sql database. So you'll use the create database and then use specify an owner optionally. So if I go in here and say create database testing, then I've created a database in here and then I can if I issue the same command again, I'll get an error saying that this database already exists. But I can say create database testing two and I can say with owner full stack course. Okay, so this basically sets me as the owner of that database. Now owners at the moment are not so useful information to really know because we're not gonna to go into so much about the permissions and attributes of users, but just know that if you want to specify a particular owner for a database, you can always say create database name of the database and then with owner the name of the role of that user. Okay, that's really good. Okay, so let's get a list of all the databases in here. You can see we have full stack course and we also have testing and testing too, but we're gonna to be able to drop those databases using the drop database command. So if you want na remove a database, you can always say drop database. So let's say drop database testing and that drop that database. And then if I issue the same thing again, you can see that I get an error saying that that doesn't exist. I can also say drop the database. Actually, let's get a list of all the databases again, a little bit smaller size perhaps in here. Let me quit this one. Let's get the list again. So I can see that testing two still exists here. So let's go ahead in here and say that I wanto drop that one as well. So let's go to drop database testing two. Oops, testing two. And that is drop map. And also, if I say drop database testing two, again, you see that alagain and error. But there is a command, which, as you can see at a bottom screen, is they drop database, if exists, testing to. And what that does is it tries to drop that database only if it exists, and it gives you a warning if it doesn't exist. However, if you say drop database and a database that doesn't exist, then you get an error, as you can see in here. So if you just want na get a warning, meaning that your command will be successful technically, but it just won't do anything, then you can say if exists, as you can see in here, you just get a note saying that it doesn't exist. Okay? So that's also a really good command to know about. So if you want to rename a database, you can always use the aldatabase. And then you say, which database? And then you rename it to an alter database. Es, I said alter, but I say alter. Nate, I think it's alter. If you're altering a database, there are so many things you can actually alter with that database. And as you can see at the bottom of the screen, rename two is just one of the things that you can change or alter inside a database. Okay, so let's go ahead and create a database again. And we say testing. And then in here we say alter database testing. Let's say rename to testing two. Okay? And if I get a list of all the databases now, you can see now the database is called testing two, okay? And then we can rename it back to testing. If we say testing two has to be renamed to testing and get a list of all the databases with backslash l. You can see now we have testing back in here. Okay, so that was about altering the name of a database. So if you want to also change the owner of a database, can you can use alter database again. But in this case, instead of saying rename to, you're saying owner two. So let's say in here, if I get a list of all the databases in here, you can see testing is owned by full stack course at the moment, which is my user. But if I want to change it to be owned by postgreuser in here, for instance, because if you issued it du command, you can see we have a user called postgres. So I can say alter database and testing and then we say owner to postgres. Okay? And if I get the list of databases again, we can see testing is now owned by postgres. I'm not by full stack course anymore. Okay? So that's also a good command to remember. Let's drop that table now. So we say drop table. I think it was called testing doesn't exist. Okay, let's get a list of all the it does exist, but it's actually owned by postgreso. Let's see if we can alter it back. So we say alter table testing owner to full stack course testing. Oh, it is not owned really by us at the moment anymore. Actually, we're sorry. We're not altering cables, we're altering databases. Sorry about that. So we say altered database testing, one or two full stack course. That's really good. Okay. And then we get a list of all the databases, not tables. And then let me just drop this database. So drop database testing, not tables, okay? It should have worked even without changing the owner. So my mistake was that I was dropping a table instead of a database. So that's very important. So if you want to drop a database, just say drop database. Okay, that's really good. Let's go ahead now and talk about creating tables. So creating tables is an operation that Jango is going to take take care of for you. So you will never really have to go ever into postgreand directly, say that you wanna create a table. But still, if you're trying to learn, sql is important to know about creating tables and databases manually as well. So the the syntax for that is create table. And you can optionally say, if not exists, the name of the table, and then you specify your columns basically. So let's go ahead in here and say, we say create table if not exists, and we name it fubar, okay? And then we say ID is serial primary key in here, okay? And let's just go ahead and create it and end your commands. Always equal ql commands with a semi column. Okay? So in here we got create table if not exists, foober, and then you can say backslash du. These are for our databases also. Let's go in here and see which database we have in here. Folstcourse, good. Okay. So now that we've created this table, let's go ahead in here and which is called fobar, we may actually want na see the list of all the tables in the system or in the current database, because if you get our current connection information, we're connected to the full stack course database. And if you want to see all the available tables in this database at the moment, you can issue the dt command, as you can see in here. So we have name, car, fubar and owner. I've already created a car and owner from before, so let me just drop them. I say drop table car and drop table owner. So if we say backslash dt, we just have fobar at the moment. So let's just go ahead with that. Okay. Now if you're curious about the scheme of the table, so how the table is created, like what the relationships are, if it has a primary key or foreign key, what columns it has, what constraints those columns have, you can always issue the backslash d and the name of your table command. So backslash d fubar, and there is no semmicolon required for psql command. So backslash d name of the table. And in here you can see the schema. Telesus is which column it has. An idea column is type is an integer. It is not knowullable, meaning it has to have a value because it was a zero al primary key. And you can see in here it says the default value is actually a function in here because when you have a serial primary key, then it uses a specific function in psql to insert new values in that column for you whenever you create a new row. Okay. So as you can see also, here is a primary key constraint on that. All right. Now if you want to drop a table, so you can just use the drop table command in here. So you say drop table fobar, okay? And if you issue the same command, again, an error, but you can always say drop table if exists and then you only get a note saying that it doesn't exist. Okay? So let's just go ahead and create that table again after we've droit here. Okay, so we have fubar. Great. Now let's talk about also auto generated identity columns. So this is a perfect way of creating primary keys. So let me actually go ahead and drop that table again, because I don't think we need fobar. Okay? So if you want to go ahead and create, for instance, a table soon, we'll do that actually right after this with a primary key. The base four primary keys in postgres is actually using an infield, which is an identity and it's always generated for you. So it's not a default identity. What that always command does at the bottom of the screen, you can change always to default, but we're not gonna na do that. But what happens is that if you go ahead and use always, then you can't change the value of that field because if in if you change it, it will always generate a new one for you. But if you say default, then when you create a new row in that table, then it generates a new ID for you. But if you go ahead and change that manually, that ID, then then you're able to do that with default. But in my opinion at least, it's always better to go ahead with always because you know that that field is always managed by psql itself. So let's go ahead and create a table. So we say create table and we call it owner, for instance, let's say an owner of a car. And then in here, we go ahead and create a field for it. So we say it has an identity. Okay, it's an integer and we say it's generated always as identity. Okay, great. And then we just issue this command and then you can see we have a creates table in here. So okay, if you want to get the schema for this table, remember you can always issue backslash d command in here. So we say owner and you can see it is a generated always as identity field, okay? However, this is not primary key yet, okay? So if you wanna make this, if you wanna make this key, primary key, you actually have to add a primary key constraint to this table creation. So let's drop that table. Then we say drop table owner, okay? And we want to now create a primary key for that table. So let's go ahead in here and say create table owner. And then you can see that we have an ID field, but at the end of the creation of the columns in sql, you can specify your constraints and the primary key constraint is just written as primary key and then parenthesis and the name of the field that has to be made into a primary key. Okay, so let's just enter this and then we do a backslash key to get the schema for this table. I we say owner, okay. And now you see that is generated always as identity and also it is a primary key in here. Okay, so that's very important if you want to create primary keys. Now now that we have primary keys, how do we go about creating a foreign keys? Now foreign keys are also constraints and you create them as you can see at the bottom of the screen with a constraint called foreign key on that column and then you say it references which primary key. So let's go ahead and create a table in here we say creates table car because we have owner and then we're gonna to go ahead and create car. Okay so let's say car itself has an ID which is an integer and then we say is generated always as identity. So this is the primary key of the car table and we that it has a we say it has for instance a let's say an owner ID owner ID in here and we say owner ID is an integer, but we haven't really basically entered any data for this owner ID. So the idea here is that the car is gonna to be a table and it has a foreign key into the owner tables primary key. So if we have an owner with an idea of one and then we have a car with an idea of one for instance or the ID of 20, the this car can have an owner ID of one meaning that it is linked to that owner with that ID. Okay, so the goal for this owner ID is to have it as a foreign key into the owner table soon as you will soon see. Okay, so first we create the column for it which is called owner ID as type integer and then we're gonna to go ahead and first of all make this ID field for the cartable a primary key. So let's a primary key ID okay and then we're going to go ahead and make this owner ID field as a foreign key. So the command for that is you say foreign key. So we say constraint a in here and we say the constraint is foreign key owner for instance. So this is the name of it for instance for us and we say it is a foreign key into the column of owner ID, and we say it references owner on its ID field like that and a sei olon. And remember, you always have to end your sql command. So the semicolon otherwise otherwise you'll be scratching your head here in the shell thinking, why is it not creating the table for me? So now we have the car table and we have the the owner table. So then what you can do in here, you can issue the dt command to get a list of all your tables. So we have a car and owner and let's get the schema for car. Okay? So you can here see that we have an ID and an owner ID and owner ID is actually actually a foreign key referencing the ID field or ID column of the owner table. Okay, so that was really a four primary keys and foreign keys. There's actually there's more to talk about, but I think we're not gonna to go ahead in too much details about primary keys and foreign keys because again, that's something that Jango will will really manage for you really well. However, sometimes when it comes to migrations in Jango, you may not know about migrations yet, but if you changing your database model in Django quite a lot and doing very complex operations, then Jango may not actually be able to do the migration for you. So it will ask you about things it would like, Oh, did you just change this field to that? Or did you did you change this primary key to that, or did you change this foreign key to another field? If it asks you those questions, then it's always beneficiary for you to know some of these basic information about sql and how primary keys and foreign keys work. So if you're curious about this type of stuff, I highly suggest that you go into psql yourself and also play with primary keys, foreign keys, tables and databases. Okay, now now that we have tables, how do we go ahead and add data to them? The format for adding data into a table in sql basically is using the insert into. So let's go ahead at the moment and get the schema for our table. So here are our tables and we are going to get the schema for for instance car you can see we have ID and owner ID but we have no name really on this car table. So let's drop the table of car. Okay and then we're gonna to go ahead and create it again. So in here we have the ID and owner ID and let's go ahead and actually create a name as well for this car. So we're going to say name is a variable characters of 255 in here. And then we make it and then we just enter this command. Okay, so now we have create table. So we have owner. And if you get the schema for owner with backslash d, you can see that it has oops, not owner. Sorry, car, car, car has a name as well. Okay, so let's go ahead and actually insert something into these tables. So in order to insert something into car, we actually have to have an owner. So let's say if we go to drop the owner as well, so drop a table owner. Table owner. Okay, yes, we can't drop that. Let's just say drop table owner cascade. I mean, I'm not gonna to go so much into details about that. What I want to do right now is to go ahead and name and add a name column to the owner table. And at the moment, I could use alter table, but we haven't gotten into details about that. So the easiest thing is to drop that table and then recreate it with a name field. However, I can't drop it at the moment, as you can see, because the car table has a foreign key relation to the ID of the owner table. So if the car table had some data, for instance, it has a car that is connected to the first owner in the owner table, then what happens if I drop the owner table? Then the relationship between that car and the owner table is going na be kind of broken, because it is connected to an owner whose table is entirely dropped. So what is happening here is that pc Maor sql in this case is telling us, though, Hey, wait a minute in here, if there are any relations between the car and the owner table, how do you want me to handle it? And by providing cascading here, what I'm saying is that if I'm deleting and dropping the entire owner table, also delete any objects that are related to admitting that if there is a car whose owner is, for instance, one of the owners in this table, you'll ete that object also from the car table. So let's issue this command. Okay, notice drop cascades to constraint and that's fine. Okay, so let's let's do D T in here. So we only have the cartable in here. Okay, so let's go ahead and create the owner table. Owner table again in here. Okay, we have ID and let's go ahead and add a name in here as a bar chart to 155. Okay? So we have owner and dt. Great stuff. So if we want to go ahead and add an owner to this table, how do we do that? So we say insert into owner and then you specify the name of the cs. So the name of the cn that we want na actually insert data into is called name, okay? And then you specify your values. So let's say the first owner is owner number one. Okay? And a semi call on. Okay. So here I shouldn't specify as single codes. I should just specify the name of the columns and sei column in here. Boom. All right. So that was the owner, okay? And that's how you insert basically values into into a table. After inserting values into the table, you of course want to go ahead and read those values. So let's insert another owner number two and then you can say select all from owner, okay? And you can see owner number one and owner number two and you can see the ID field is actually being auto incremented for us. So we didn't have to insert any ids into the table off owner. Okay? So if there is any fields that you have in your table and you want to make sure that those fields are never left empty, then you can use the not null value, basically, sorry, the not null constraint telling the column not to ever have the value of null, meaning that it has to always have a value. Okay. Now we are now going to go ahead and create our test tables. As you can see, offset that, we need to create the owner and the car tables with name fields of vchartwo hundred 55 and farkey and ID. But we've already done that. So we've already created these tables. So if you haven't done the owner and the car tables, here's how you create the owner table. All right? And this is how you would create the car table. Okay? So you can pause the video at those points and then go ahead and create these test tables because they're kind of important for the rest of this chapter, let's go ahead and insert some test values into our tables. So if you say select all from owner, we have two owners. But if you say select all from car, we don't have any cars. So if we if we get the schema for the car table, we can see that we have ID, owner ID and also name. So let's go ahead and create, for instance, a Tesla car with the owner ID of one. All right. So let's say insert into owner into the fields of owner ID and also name. And then the values are one and the name is Tesla Model x vas in here. Okay. And then the same I column and here is saying call owner idea relation owner does not exist. Insert into owner owner ID, name values one. Okay. Let's get, let's get the schema for our car again. Car we can see owner ID is here and it's generated as always. Okay. Owner ID integer. I see. I think the owner ID is kind of like the the foreign key has kind of disappeared. So let me just drop this table, drop table car and let's go ahead and create it again in here. Let's see here like that sei call on. All right, so let's insert into that now. Oh, we're getting a relation does not exist. And I can see actually now what the problem is because we're inserting into owner, but we should be inserting into car. So let me go ahead in here and say inserting into car. Now we can see that we've inserted a Tesla Model x with the owner ID of one into the car table. But if I go ahead and insert, for instance, owner with an ID of 1000 in here, you can see where are getting an error from A C L telling us that an owner on the owner table with that ID which you're inserting into the car table does not exist. So the foreign key is working quite fine. Alright, right now, how do you go ahead and delete data from a table? So if you go ahead in here, let's go into our owner's table. So we say select all owner. Okay? And we can see we have owner one, two. Let's go ahead and insert some more owners. So let's go ahead in here, your owner number two and let's go ahead and insert owner number three. And also if I want to insert owner number three again, I can just say backslash g. And you can see that same command was issued again. So that's where backslash g is quite useful. Okay? And let's grab all the owners. Now we can see that we have one, two, three, three, okay? And if you wanna delete all the rows in this table whose name is owner number three, then you can issue the delete command. You can see delete from table where some condition is met. So we say delete from or where name is equal to owner number three. Actually, here, it should be a single code. So we say owner number of three and sei call on. And you can see there are two rows that were affected. So if we say select all from owner, we don't have owner number three anymore. So we can insert it again if you want to and then backslag. And then we have two owner number three es again. Okay. And their iare different now. Good stuff. If you want to delete all the rows inside. And so if you want to delete all the rows inside a table, you can just say delete from owner. But this is very rarely used. I mean, I don't really use this command almost never. But if you're sometimes you're trying to clean some tables, for instance, and you're testing out things, then you may need this command. So you usually say delete from, as you can see in here, delete from where a condition is met. But if you just say delete from that table, then everything is going to be deleted. But just please be careful with this command because you most certainly never almost never want to issue this command for instance in production environment, okay? Because Yeah all your data for a specific table is gonna to be gone unless that's specifically what you want to do in production okay? Okay, so if you want to select all rows from a table we've already done this where you can issue the select spar from owner for instance and you get all the rows in that table. Okay, now if you want na select a specific column, so for instance, you just want na see the names, you can just say select name from owner. Owner like this, you only see the names so you don't see the ids. And you can also specify select here and let me just see select ID and name from owner. You can also specify with a column in between the column names to get multiple columns. Okay. And actually that's something that I think I ran ahead on myself, but if you want to select multiple columns, you then specify a little column between the column names in here. Okay, all right, that's really good. Now when you get then more and more into sql, you sometimes may want to, for instance, do some operations of select operations where you're being very specific about what you want. Now in here we have two owner number three s. Okay? And if you want to, for instance, grab any row from this table whose owner name starts with ow, for instance, then you can basically issue the command as shown at the bottom screen. You can say select everything from owner where name like. And then you say you start the string, how it basically gets started. And then you say percentage. And you can see it basically shows you the name. It shows you all the rows who's name starts with ow and then anything after that. Okay, now you can also go ahead and change the position of this percentage mark to the beginning of the string, meaning that anything it starts with anything, but it can end with a specific thing. So in here, let's select everything from owner again. So you may be looking for owners who end with number three. Then you can say select from owner where name is anything but. It should always end with number three, okay? And you only get owners whose name ends with number three, okay? Now if you want to, and as you can guess now, if the percentage sign in the beginning means that anything and then ends with something and at the end it means starts with something and it ends with anything, then the percentage sign is kind of like is kind of like a wildcard match sign basically. So if you want to find strings that contain a specific value, so at the beginning doesn't matter, the n doesn't matter, only you're only interested in what it contains in the middle, then you can use this syntax percentage percentage and then you write something in here. Okay? You can see this says, okay, here are all the names that have any in the middle. And you can also say like this, so it doesn't necessarily have to be in the middle, but it is anywhere in the string itself. Okay, so there is lots more to sql as you can see at the bottom of the screen. I mean, if I want to create a sql course, it would I think it would be upwards of 20, 30 hours. There are some good sql courses out there if you're interested in sql as as itself. And I know free code cam has a beta or beta version of one of their relational database management systems courses out there, so you're more welcome to test that out if you're specifically interested in working with sql. But when it comes to Jango, as you'll soon see when we get into development of our Jango application, you don't really need to know sql. I mean, it's kind of I always suggest actually any software developer to learn sql because it's such an important skill these days, specifically to learn how to work with sql. Even if you're just doing front end development, you're most definitely or going na get to a point where you need to know sql. Even if you're working with firebase, sometimes you may need to know the basics of sql to understand how firebase works, even though it's a document based storage kind of or it has that functionality at least is firebase is a lot more than that. What I think is that you should be aware that when you get to Jango, you don't have to know sql, but it is always a huge plus if you can work with sql. So go ahead and look at that free code camp link please. And if you have free time, go ahead and learn more about sql or at least experiment with it. Okay, so I give you a huge congratulations here because I think now you know at least the basics of postgres and sql in here. You know some of the basic commands of working with postgres, seeing databases roles, you can see tables, you can issue previous commands and Yeah the basics. You can see the schemas of tables. And there's lots more to psql commands, which you can get basically with backslash question mark. So if you're curious, you're more welcome to just go ahead and explore this commands. And maybe there are some more commands that are interesting, which you think the community needs to know. In that case, please go ahead and leave them in a comment section at the bottom of this video. Or if you have any questions, also, please let me know. Don't forget to join our discord group. The link to the discord group, you can find it in the playlist for the free full stack course. The link to the free full stack courses playlist is the first link in the description of this video. Go ahead and open that, please. And then the discord invitation is also in there. So I hope you enjoyed this chapter, and I'll see you in the next one.
最新摘要 (详细摘要)
概览/核心摘要 (Executive Summary)
该视频是为使用Django框架的开发者提供的PostgreSQL速成课程。讲者强调,尽管Django通过其ORM(对象关系映射)极大地抽象和简化了数据库操作,使得开发者通常无需直接编写SQL查询,但理解PostgreSQL的基础知识仍然非常有益。这有助于开发者更好地理解底层工作原理、处理复杂的数据库迁移以及提升解决问题的能力。
课程内容涵盖了从连接数据库、管理用户角色,到数据库和数据表的完整生命周期管理(创建、重命名、删除),再到核心的数据操作(增、删、查)。重点介绍了psql命令行工具中的常用命令(如 \c, \l, \d, \dt)和标准的SQL命令(如 CREATE, ALTER, DROP, INSERT, SELECT, DELETE)。课程还详细解释了主键(Primary Key)、外键(Foreign Key)的创建和作用,以及如何使用 LIKE 操作符进行模糊查询。讲者最终的结论是,虽然在Django开发中不强制要求精通SQL,但掌握SQL是一项对任何软件开发者(包括前端)都至关重要的宝贵技能,并鼓励学习者深入探索。
课程目标与核心理念
- Django对数据库的抽象:讲者开篇指出,Django为开发者抽象了大量的数据库管理工作。在使用Django时,开发者通常不需要直接与PostgreSQL、MySQL或SQLite等数据库进行交互或编写原生SQL查询。
> "when we get started with the back end development using Jango, Jango abstracts away quite a lot of database management for us. That means really that you don't have to work directly actually with postgres or any other database for that matter..." - 学习基础知识的必要性:尽管有Django的抽象层,学习PostgreSQL的基础知识依然有以下好处:
- 理解数据库在底层是如何工作的。
- 了解PostgreSQL与标准SQL的关系。
- 在处理复杂的数据库迁移(Migration)时,当Django无法自动处理时,这些知识将变得至关重要。
- 课程范围:本课程旨在介绍PostgreSQL的基础,而非进行深入全面的教学。
PostgreSQL 基础命令 (psql)
视频演示了在psql交互式终端中使用的多种便捷命令,这些命令以反斜杠 \ 开头。
- 连接信息:
\c或\conninfo: 显示当前连接的数据库、用户、端口等详细信息。- 默认端口: 视频强调PostgreSQL的默认端口是
5432,这在后续配置Django时会用到。
- 用户与角色:
\du: 列出系统中所有的用户(在PostgreSQL中称为“角色 (Roles)”)及其权限属性(Attributes)。
- 数据库列表:
\l: 列出当前PostgreSQL实例中所有可用的数据库。
- 数据表操作:
\dt: 列出当前数据库中所有的表。\d [table_name]: 显示指定表的结构(Schema),包括列名、数据类型、约束(如非空、主键、外键)等。
- 命令与会话:
\s: 显示历史执行过的命令。\g: 重新执行上一条命令,在重复插入数据时非常有用。\?: 获取所有\命令的帮助列表。\q或quit: 退出psql终端。
- 版本查询:
SELECT version();: 一个标准的SQL函数调用,用于查询当前PostgreSQL的版本信息,在寻求在线帮助时非常有用。
数据库管理 (Database Management)
课程讲解了使用SQL命令对数据库进行的基本管理操作。
- 创建数据库:
CREATE DATABASE testing;- 可以指定所有者:
CREATE DATABASE testing2 WITH OWNER full_stack_course;
- 删除数据库:
DROP DATABASE testing;- 为避免因数据库不存在而出错,推荐使用更安全的方式:
DROP DATABASE IF EXISTS testing2;(这只会产生一个提示而不是错误)。
- 重命名数据库:
ALTER DATABASE testing RENAME TO testing2;
- 更改数据库所有者:
ALTER DATABASE testing OWNER TO postgres;
数据表管理 (Table Management)
这是课程的核心部分,详细讲解了表的创建、结构定义和删除。
- 创建表 (
CREATE TABLE):- 基本语法:
CREATE TABLE [IF NOT EXISTS] table_name (column_name data_type [constraints], ...); - 自增ID与主键:
id SERIAL PRIMARY KEY: 一种简便的创建自增整数主键的方式。id INTEGER GENERATED ALWAYS AS IDENTITY: 讲者推荐的更现代、更标准的创建自增ID的方式。ALWAYS关键字确保该值由系统生成,用户不能手动覆盖。
- 主键约束: 可以单独定义主键:
PRIMARY KEY (id)。 - 外键约束: 用于建立表与表之间的关联。
>CONSTRAINT fk_owner FOREIGN KEY (owner_id) REFERENCES owner(id)- 这行代码定义了一个名为
fk_owner的外键约束,将当前表的owner_id列关联到owner表的id列。
- 这行代码定义了一个名为
- 非空约束:
NOT NULL确保列必须有值。
- 基本语法:
- 删除表 (
DROP TABLE):DROP TABLE fubar;- 安全删除:
DROP TABLE IF EXISTS fubar; - 级联删除: 当表之间存在外键依赖时,直接删除主表会失败。可以使用
CASCADE关键字强制删除该表及其所有相关依赖。
>DROP TABLE owner CASCADE;
数据操作语言 (DML) 基础
课程演示了对表中数据进行增、删、查的基本操作。
- 插入数据 (
INSERT):- 语法:
INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2'); - 讲者演示了如果插入一个在外键表中不存在的ID,PostgreSQL会因违反外键约束而报错,证明了数据完整性得到了保障。
- 语法:
- 查询数据 (
SELECT):- 查询所有列:
SELECT * FROM owner; - 查询指定列:
SELECT name FROM owner;或SELECT id, name FROM owner; - 条件查询与模式匹配 (
LIKE):WHERE name LIKE 'ow%': 查找name以 "ow" 开头的记录。WHERE name LIKE '%3': 查找name以 "3" 结尾的记录。WHERE name LIKE '%any%': 查找name包含 "any" 字符串的记录。
- 查询所有列:
- 删除数据 (
DELETE):- 删除符合条件的行:
DELETE FROM owner WHERE name = 'owner number 3'; - 删除所有行:
DELETE FROM owner;- 警告: 讲者特别强调,这是一个非常危险的操作,尤其是在生产环境中,应极度谨慎使用。
- 删除符合条件的行:
结论与建议
- SQL对开发者的价值: 讲者重申,尽管Django开发者不常直接编写SQL,但学习SQL是一项极其重要的技能。
> "I always suggest actually any software developer to learn sql because it's such an important skill these days, specifically to learn how to work with sql. Even if you're just doing front end development, you're most definitely or going na get to a point where you need to know sql." - 后续学习: 鼓励对SQL感兴趣的学习者探索更多资源,例如FreeCodeCamp提供的相关课程。
- 社区互动: 邀请学习者加入课程的Discord社群进行提问和交流。