Introduction to Django Models

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to our lecture on simple django models now as you've seen in previous lectures we talked about SQL structured query language and that's how we talk to databases and it's beautiful because it allows portability up to a point across databases and we talked about all the create tables stuff and so this is just a bit of review where you know we can type these commands to SQLite we run SQL Lite we run a create table statement and you know we do it to say dot tables there we go we can ask kind of schema users we did all this in a previous lecture and and so that that's basically how SQL works and here's a series of SQL commands from a previous lecture just kind of as review it's pretty simple crud now one of the problems is is as I mentioned is that different databases like Postgres in mysql do all this stuff identical but then some more subtle things like how foreign keys work which we'll learn in a bit or how they do limits like pulling like twenty five next twenty five next twenty five a little bit different and so if you want to build an application that talks across more than one database you've got to think a little bit and one solution to this also to kind of limit the fancy SQL you have to learn i like to say that you know you can learn the first 60 percent of SQL in about three hours and the last forty percent is literally a lifetime i mean and so it's advanced SQL is difficult to do maleeh hard to teach a class in advanced SQL I can teach you advanced features but then there are so many features that you you just can't learn in a class which database you're using they're different for every database so one thing that's happened in the past decade or so is the emergence of what's called object relational mapper and that is to in the you have the physical database layer and then you have SQL which is an abstraction it's a imperfect abstraction and then Django builds another abstraction on top of that called object relational mapper so we just create Python object and we ask that to be placed in the table no the object may have a name an email address and you know a birthday or something in it it can have all kinds of data in that object and then that map's into a name and an email address and we have to tell it like do we want this to be indexed and all these other kinds of things we communicate through the ORM so we we leave the or I'm alone now in Django as we get more advanced you can also sort of bypass the ORM because the the way the objects are mapped into the tables is predictable the names of the columns is predictable and so it's kind of like it's a it's a shortcut for I like to think it's like that eighty percent mo of the most common things you do with a database are easily done with an object relational model but object or M but but ultimately once you get to the more advanced things you tend to not be able to do that with a nor am I use you get you get to the point where writing SQL is easier than using the Oram but for about 80 percent writing ORM code is way easier than writing the SQL the other thing that RM does is it allows you to have multiple databases because the ORM code inside of Django knows the difference between SQLite Postgres and MySQL and so you could actually start at an application that uses us light during all your development and then when you've devoted to production you just go like you know what let's just use MySQL or Postgres and that's quite cool I find them limiting and so just I want you to know both how to use objects and how to use SQL but understand that most of what you're going to do is to use the object relational mapping and we get a lot of power with with this so if we look at sort of the the way we communicate to the database or the way we define the database in SQL we create a table and that that right there is portable but once you start doing things like adding auto-increment columns and things like that it stops being portable and so that's the way we do it but in Django the way we do this is we have a file called models dot py and it's it's in the application folder and then we are going to use object orientation so we're gonna from Django DB that's a package we're going to import models and models is now a class and we're going to create a class called user this is going to be equivalent to the name of table and we're going to in in in in kind of the definition we're going to extend models dot model and so so there's a lot of it this is called extending it's called inheritance we're going to get a lot of features and functionality excuse me we're gonna get a lot of pictures and functionality from this code so there's probably 20,000 lines of fancy code that we didn't write that we're using by extending models model we're getting all that and then within here we create a couple of attributes that basically says give me a character field models is a class char field is a method within that class max length equals 128 and that gives us the name these two things are equivalent and what happens is is when we build this and we do what's called run a migration then jangle will make this table for us but then we have this abstraction that we can use to talk to it so this is called a migration and so you have to be in the projects folder and so once you create a migration inside of your Django application then you go up into the Django project and you say Python 3 manage py now manage to py is kind of like the thing that starts everything so make migrations is actually creating files because the idea with migrations is that you would debug your migrations like on your development environment and then once you know you would move them to production so you'd make the migrations and development environment you get them right and then you'd like check them into github perhaps and then in production you would pull your migrations out of github and then the migrate so to make migrations to make migrations that that is creating a set of migration scripts and you can see that it's making these files and their actual files and you can go find those files like oh one initial P Y and then the migrate is reading the migrations and then actually changing the database so that's the one where you might be able to make a migration in that and it doesn't matter what database you're going to use could be your development in SQLite and production in MySQL you would do migrate in both of those and in your development it would make an SQLite database in your production it would make an - ql database i'll put the tables in and the SQL might even be quite subtle and it will be subtly different between them but you don't care so migrate is the act of creating the database now in our development environments we're going to be creating a file called DB sqlite3 and so if you get all messed up you don't have to remake your migrations they're just sitting there kind of as part of your source code and you can like get rid of the demon sqlite3 file and then run the migrations again if you get kind of messed up so them the the make migrations reads this and creates these other little files you can take a look at them they're kind of like Django's internal files they're Python it's just you're not going to write them by by yourself but then the migrate reads the o1 initial dot py and then actually creates SQL commands and runs those SQL commands for us and so if we jump after we've done this we see this file DB SQL i3 and we can jump in and take a look again you have to be in the right folder so you'd be in the Django underscore projects and then the folder of the project but there'd be a file called even SQLite 3 go into a Linux command line type SQLite 3 DB SQLite 3 and you will find a whole bunch of things yeah when you go into SQLite you type tables you will see that Django has a bunch of migrations that are all there from the sessions and stuff we're going to learn how to use later authorization etc etc but then the particular data model that you created which is a user data model there's a table in there for that and if we use the the schema command of SQL I 3 and we say hey what is in that user model under our user table and it's you see a create statement right and so this is the actual create statement that that the Django sent to SQLite to create the table and I was talking about some of these things are quite predictable the name of the column is quite predictable ID name email cetera it has the ID field for you automatically and most of its portable like this part here is quite portable but this ID statement here primary key auto-increment turns out that little if you're in MySQL or Oracle or Postgres rescue like that's a little different but literally the migrate takes care of all that because the migrate knows that thing and as MySQL changes that particular syntax doesn't change very much but as MySQL changes then the Django stuff changes and it all kind of works out and so you can sort of run these commands and then sneak back into the database and you can see what they've done but it's it's all very predictable want to spill my coffee on my computer so you can also talk you're talking at the low level when you run the SQL like command but you can also be in that folder same folder that has DB SQLite and manage dot py and then you can start what's called the shell so this is different than the linux shell and you see the prompt change from dollar sign to three three chevrons and it's not the same as the Python shell although it is the same as the Python shell with a whole bunch of Django libraries that are pre mounted okay and so if you just say Python 3 you'll get this but you but this next command that is from user model models import user that will fail unless you let manage dot py start your shell because again it loads a bunch of objects and classes into your space and then all of a sudden user model models works users there etc ok so this is pulling from your models py file that you built and so user model as the application name in models is the models dot py file we import the user model which is in this case a class user is a class and we're going to do a constructor call and so we're gonna say let's make a new user set the name to Kristen and the email to that email and this actually has not done anything in the database this creates in effect just a Python variable and then to force it to read written to the database we call you dot save and so save as a method on this new user object capital user capital user is a class we're using a constructor to construct from the class an actual instance an object and we get that into you the instance object and then that object sits in our memory until we say save and then it also pushes it back to the database now one of the things that the save does it assigns an effect a serial number or a row ID the yeope you look at these they start pretty predictably at one two three four five but if you're getting a bunch of things coming in from a bunch of places then the database just assigns each object each row and that's part of that whole auto increment thing c'mon go back up this whole auto increment thing that says hey database I'm going to put your records in I'm gonna give you the name of the email and you come up with a number but then when you're done I want you to tell me what the number is and this is how you get that number by saying Oprah new dot ID now if you printed you dot ID before you did to save it wouldn't exist and then print you dot email you can see this email is just the data we put in but now this is not only in your you variable but it's also in the database as well okay now we can dig a little bit into how this object relational mapping is working and so if you if you're in the middle you're doing things like that last statement you can from Django DB import connection and then ask connection queries and then what it does it just shows you a little bit of debug data and what it did how it started the fact that it ran an insert statement and again this looks kind of familiar this is just making up SQL for you for that insert the save statement write that save statement there it's making that insert for you and then you can actually see what it's doing right and and and so there save you know set up a thing and save it you don't need to know insert into or whatever because that's because the object relational model does it for you right and this is kind of what we did before insert into capital users by hand and so again it you know this you'll find this ORM is gonna save you a whole bunch of time for eighty percent of the things that you do with the database and so you can do basic crud operations with this object relational mapper the save is the insert you can select is basically user object values that's like select star so give me all of the objects a where Clause is user objects filter and there's your where clause this is a emails a column name and c7 umich.edu is a value in that column values is actually go get them so you can create kind of a query so if you don't put values on you get sort of a query that's not yet executed and then value says go do it do it now you so you can do a different well you can delete something where you say and so this is a little different syntax this is kind of a selector that says these are the variables to select and dot delete says I mean the rows to select and then delete those roles value says retrieve the rows delete says get rid of the rows and then you can again the same kind of thing this is kind of like a where Clause user objects filter email equal c70 Majidi u dot update and then change this column in a way and you can you know go retrieve all the values and there are things that correspond to lots of the SQL like give me all these values order by email etc etc etc so it there it's it's kind of a one-to-one mapping and you will again I you're going to do a lot of programming using this ORM in Django and every once in a while you'll sneak down to SQL and that's why I sort of teach you the SQL first and there's lots and lots of fields that might not actually be represented exactly the same way in the database so for example an email field databases we don't have email fields there might be some databases that have emails I know that don't but because the object relational mapper is a layer between you and the database and you say I'd like this to be an email field then it can add rules and stuff like validity checking etc to say you know what that doesn't look like an email address and so there's all of these things and these are these are very useful and later we'll talk about connecting tables and we'll use things like foreign keys and many too many fields and one one fields and those are more those are less about the data and more about the connections between tables which we'll talk in coming up soon and so just to give you a sort of a bit of a sense of where you're at this is our application right and so we have a browser on the left-hand side with a user doing some clicking by now you may have created a URLs py file and that takes the the syntax of the get request slash this slash that slash whatever and routes it to a particular view coming from the views dot py file you may or may not have made one of those templates and forms help produce output but the models are our interaction between us and the database and so the actual code we write in Django can talk through the models to the database which you may not have done yet but this shell is talking through the Django models to the database as well and if you're starting to use the admin user interface the in user interface talks to the database to the models and it's informed by the kind of things that you add to add mint to use the Django admin interface and have your models shown a particular way it's got a bunch of defaults but often you want to override those defaults and so that's what you put in and the model dot py file informs this connection between the database and it also sort of informs the kind of code you write here in a view code in Python or in the Python shell that's kind of the Django shell which is a Python shell with all that stuff added to it okay so this model dot py is critical to defining our relationship between all of our Python code in user interface and the actual database and and so you'll see a recorded demo where I go through a bunch of those things which I kind of just showed you it's just actually doing it in a demo form but it's almost Lee in this lecture and so the Django model is Django's version of an object relational mapper you can write Python code after a while especially if you you know have an IDE that can show you what objects have and stuff you tender it's a lot easier to write whereas SQL you have to know it and write it you gain database portability you can create these migrations to both build your initial schema in your database and then evolve that schema as your application involves that's one of the more valuable things if you're building straight-up SQL going from like version one of your database to version two of your database it is kind of frustrating and difficult sometimes migrating and evolving a database is harder than actually writing the SQL code in the first place and Django gives you right out of the box that's a really cool administrator interface the models and models Kahwa PI and admin pouch and later we're going to have all this automatic form generation and so what we're doing here is it seems like we've put like three lines of code into some file and it will all bunch of magic happens and that's really how Django works and the idea is is that way you as the developer can focus on the columns of your database and the forms that you want to put up and spend less and less time sort of manually building kentuc HTML it's very sort of brittle and SQL that's less brittle but still brittle and so that's the idea and so it's a little hard when you're getting started because you're like just the amount of code you write is so small and the amount a comp what that accomplishes is so great but after a while when you get all these little tiny pieces figured out then all of a sudden you're like okay now I want to solve that and users problem and you can spend all your time solving that problem rather than just making databases and those kinds of things so see in the next lecture Cheers [Music] [Applause] [Music]
Info
Channel: Chuck Severance
Views: 6,100
Rating: undefined out of 5
Keywords:
Id: AqsPifp-ccc
Channel Id: undefined
Length: 19min 59sec (1199 seconds)
Published: Wed Sep 11 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.