How to Do Database Stuff with Django Models (without knowing SQL)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to be working with Django models and Django models makes it so simple and convenient to interact with a database without knowing SQL language or a database language we can interact with a database with python and python only out of the box it's really cool stuff let me show you how it works let me first tell you what kind of data I want to work with I want to be able to keep a track of a list of scores let's say I'm a teacher and I want to keep a database of my students test results so Alex got a 99 Robert got a 74 let's say I want to be able to add Janelle got a 89 and Andrea got a 53. you get the idea we want a name and a score associated with it I want to be able to add to that list take away from that list modify the list all that good stuff so let's do that inside your Django project make sure in your project when you have your virtual environment active let's go into our app directory which we have named score which is appropriate whoops LS everyone and go CD score and in here there is a file called models.pi so this is where we're going to Define our model which again is just a representation in Python of what's going to be in the database so let's define our score model so it's going to be a class called score and it's going to be of type models which we're importing here dot model okay we're just inheriting from model and it's going to have two Fields the name and the score so let's do that name and the type of the name is going to be models Dot Char field and Char here is just short for character character field like letters with a max length of 50. so you can have a name that's between um 0 in 50 letters the other field we're going to have is called value I'm going to call the the score itself the value that they got on the test and that's going to be of type models.positive small integer field and as the name kind of implies it's just a small positive integer you know one two three four we only need to keep track of scores between 0 and 100 and that will be sufficient for us so let's go ahead and save that file now that we have defined what our data is going to look like and let's create our database syntax now we don't again we don't need to know anything about databases we just execute a command in Python Django does it all behind the scenes for us so that command is going to be well first of all let's go to our root of our project and that's command's going to be python manage dot Pi make migrations now a migration is uh and I'll actually show you what the migration looks like it's making this python file that's going to communicate with the database in the back end so let's see what that looks like with python manage.pi SQL migrate the name of our app score and then the name of the migration which here is zero zero zero one so all this did is looked at our model and defining the database Syntax for us so it's going to create a table and it's going to have an ID column which we don't need to worry about at this point and it's going to have a name with a variable character field up to 50 characters and it's going to have a value field that's a small integer greater than or equal to zero so let's in human readable terms kind of what we wanted to do but it was a lot easier to just Define that in Python now I mentioned this in a previous video but we do have a migrations folder inside of our app directory and that's where that migration lives okay so now that we've defined the migration let's actually execute that database code in our database which by the way out of the box default for Django is in this database.sql lite3 file okay that could be anything I'll just mention this real quick that could be any database a postgres database a mySQL database Maria database any of that stuff but we're just going to use the default database out of the box so let's apply those that database migration to the actual database let's execute that code with python manage dot Pi migrate and this is going to do a whole heck of a lot of stuff because this is the first time we're doing a migration so it's going to take care of a lot of back-end stuff that we're going to use later on in this tutorial such as the admin console in the Authentication tables that it needs to keep track of users and then you see down here our score migration being applied to the database all right we have done enough at this point to be able to start adding data to our database so let's go ahead and do that and the way we're going to do that is with the python Django shell so let me show you how to access that we're going to type in Python manage.pi shell and that brings us to this interactive python console where we can import different Django packages and test things out and interact with our database it's a great way to do all that type of testing before you implement things into your website so let me show you how that works we have access like I said to our Django packages so in order to import our score object that we just created we can do that with from score dot models import score so that is basically the path in our our Django project so the app directory called score there's a file in there called models.pi in in that file called models.pi there's a class that we just defined called score so we're going to bring that into our python Django shell here and now we can see what kind of data we have in there so we can check that with score dot objects dot all and right now there are no scores we haven't added any scores to the database yet but let's go ahead and do that I'm going to make a score object in the Syntax for instantiating a new object is going to be the name of the class s-c-o-r-e and then the parameters that you're going to pass into that so the name is going to be Tony and the value is going to be let's say I got a 95. so we'll head enter and now we have a score object and we can do things with the score object like score what's the name Tony what was the score that Tony got 95. now this isn't in the database yet we can save it to the database with something like this score dot save hit enter and now that data has been saved to our database and we can verify that by pulling down all of our score objects again with score.objects.all and before we had an empty query set and now we have a query set with just one object in it and that makes sense because there's only one row in the database I'm going to go ahead and add some more scores to our database just so we have some data to work with and I'm going to paste that in here so I added four more scores to our database Alex Robert Andrea and Janelle so if we check all of our score objects again now we have this with one two three four five objects as expected now there's one modification that I want to make to our model and that's how it's printing it out on the console so we're seeing this kind of ugly syntax score colon score object one score we don't really know what that score object is until we access it directly but let me show you how we can give that a better string name and inside of our score directory in our models.pi file we can simply add another function in here that looks something like this so Def underscore underscore Str underscore underscore self and then that's going to return self.name now what the heck what what does this mean basically whenever you print out a score object on the command line it needs to print out a string and the default string is going to be at this point self.name so self is this object that you're currently working with and then the name field here so it's going to just print out self.name which is the name of the person so let me show you how that changes things back on our python shell we can import our score model again and we will do score.objects.all and now instead of seeing you know that object one object two we see the score with the actual name of the the person who got that score okay that's cool let's take it a step further and do some filtering and sorting and show you how to interact with the data in a different way so let's go ahead and make a new variable called scores and we're just going to do like we were doing score dot objects dot all so now our score.objects at all is stored in this variable called scores and we can Loop over that so for score in scores let's print something out to the console that says this person got a this score and we can format that with the score dot name and the score dot value so let me explain this in case you're not familiar with this syntax this is creating a string the first argument to the string is going to be the name of the person and then the second argument is going to be the value of the score for that person so if we execute that we should see five lines Tony got a 95 alkaline 99 so on and so forth now what if we wanted to print those out in order well we can do that in a very similar way for score in scores dot order by value okay we want to order them by the score that the the person got we can print out the same exact stuff hit enter now Robert's at the bottom of the top of the list with the smallest score and Alex is at the top of the bottom of the list with the biggest score um if we wanted to do that in the reverse order we can do order by value descending equals false and then we'll print them out okay my bad I really over thought that we don't need an extra argument here Django makes it pretty easy you just have to put a minus sign in front of it to to kind of negate the order so for score in scores dot order by minus value we can print the scores out and now top score is going to be at the top and bottom score is going to be at the bottom Perfect all right let's do some filtering let's define a new variable called high scores and that's going to be score dot objects and instead of all this time we'll do filter and then what's our filter going to look like our filter is going to be value we only want values greater than or equal to 90. okay what is this so we're applying a filter and Django has this pretty neat syntax where you can specify a field name here a double underscore and then they have all these predefined filter filters that you can use like GT for greater than GTE for greater than equal LT for less than LTE for less than equal and that's going to queer the database and only return the records that match that query so let's see if that works let's get only the people with scores higher than 90. and we can do something similar that we did before so and just so we can save some time here for score in high scores dot order by value we're going to print the same type of thing this person got this score hit enter and as expected we only see scores above 90 or equal to 90. now another filter that we can do is on a string so there's a whole bunch of different string filters too that you can apply and again I'm gonna for for the sake of brevity so you don't have to watch me type I'm going to Define this by copying and pasting it so names that start with a okay so a variable called a names we're going to do score.objects.filter same type of thing the field name double underscore starts with that's our filter this time starts with and then the letter A so let's see if that works I'm going to copy and paste the for Loop here hit enter so now we only see names with a Alex and Andrea interacting with Django models on the command line is great but an even easier way to interact with them is using the Django admin console which we'll be talking about in the next video foreign [Music]
Info
Channel: Tony Teaches Tech
Views: 2,580
Rating: undefined out of 5
Keywords: django database, django gte, django model, django model fields, django model save, django models, django models tutorial, django objects all, django objects filter, django save, django startswith, how to use django models, models django, python manage.py shell
Id: NeEmegB9gwQ
Channel Id: undefined
Length: 13min 47sec (827 seconds)
Published: Thu Aug 03 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.