Django Models | Crash Course | Field Types, Connections, and Model Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys in this video I'm going to talk about database models in Jango I will talk about how to design them how things are connected to each other and give you some examples so if you're interested in learning more about Jango database models then this is the video for you so we are going to end up with something like this as you can see down here just want to see the canvas here so you can see we have a few tables and I'm going to show you how to set up everything of this how these are connected through forine Keys many to many fields and what to use when and where so I'm just going to begin with an empty document here in this eraser app just to see where we start as the base but before I do anything more here I just want to show you that here in Visual Studio code I have a completely blank jungle project nothing in it no apps or anything so before you continue maybe you want to create an empty jangle project so let me just create a new empty project here new file just so that we can begin at the beginning okay let me just remove everything here so built into D Jango we have something called the user database model this handles everything from uh email username first and last name when the user was created handling password and similar so I'm just going to set it up here so you can see how we're going to connect this to other things in jangle you don't have to think about the syntax on this this is just for setting up the table here so usually each of these fields have an ID almost all tables in Jango have an ID which is default a big int which is a big integer and this is usually also the primary key so you can refer to this as the ID or the PK and then we have the first name here as well first name which is usually a Char field and a Char field is a field where we can store things like name last name title for blog posts and the other types of strings that is usually less than 255 characters so I'm not going to to add more to this because I just want to show you how the user database table is connected to other tables in a system so let me just set up one more table here this going to be a team so the example I'm going to use in this tutorial will be something similar to a project management system where you usually have a team and a team can have multiple members or users and the team can also have projects and the project can have to-do list and the two to-do lists can have tasks so then you might wonder how can we connect two tables to each other for this we're going to use a called f for rine key so here I can add a new field called users man to man field and by the way I will show you in Jango later later in the tutorial how to set up all of this so right now this is just to show you how it is connected and the team should also have a name variable so name this can be chart field and the ID like that so how can you connect this field to this now that is where the man to many field comes in what this means is that the team can have multiple users in this field here and a user can also be member or a user in multiple teams so let me just connect these two by setting team. users point that to user. ID so now you can see that this field here is now connected to this one so let's return to Jango and set this up before we continue continue adding more stuff so right now we just have the default Jango project so let's create a new app for the teams so project sorry python mentioned by start app team then we can add this to the database sorry we can add this to install apps team and then in here we create the database model for the teams so class team models. model and then you can see here in this app that I have ID field this is default for Jango so I don't have to add this but I want the name and that is the name for the team set this to be a Char field and set the MOX length to 255 and then I want the users field here users equals models do man to man field user like that okay so you see here I get a warning because user is not defined so let's import this from D Jango from Jango comb. or. models import user I think this should be correct it's probably just my editor that can't find this so now we have a connection between the team and the built-in database model user so if I now save and run the make migrations to create the database file python mention by migrate great so now we have this now we have a connection there I can create a super user just so that we can log into admin interface and test this python me pi create super user great so then I can run the server as well and open it in the browser so if I go to slash admin I can log in with the user I just created I can see here that I have one user the admin user but team isn't appearing there because you need to add it here first from do models import team admin. site. register team so now we should be able to use this here in the admin interface so if I now create a new team team one can have this user save so if we go in here again now you can see that the name of the team and the connection to this one and this connection is done through this one here nice okay so let's expand a little bit on this now I want a team to be able to have multiple clients and a client can for example be let's say that you run a web agency and you have multiple clients so let's just create that first here very quick client icon can just use the user icon here as well and this should also have the big integer primary key field and I want a reference from the client back to the team and since a project should only be able to have one team and A Team should be able to have multiple clients we can't use the man to Manu field here so here we will need to use the forign key on the client table so here as a team for R key for aops key and I want the name field here as well so I can copy that from the team there and I want to know when this was created so created at should be a date time field okay so what I need to do now is to have a connection between this and this so connection between these two so down here I can just say client. team point that to team. ID so if I just zoom out whoops a little bit you can see here that the team is now connected to the users but the team ID is also connected to the team field on the client side okay so if I now say that I want a new app for the client as well then I need to create that here so python meure Pi start app client before I continue I just want to say thanks to all of my patrons if you do want to support me you will find a link in the description below and then we can create the database model for this as well so here I need to import the team model from team. Models import team then I can just create it close client pass in models. model and we can begin with the team reference team equals uh models do forign key plus team and then we need to set uh something called the relate name and this can be clients so what this does is that it makes it very easy to get all of the clients connected to team so for example in a template or in a view you can just say team. client. all to get all of the clients that are connected to that team and the last attribute is something called on delete and we can say models. Cascade so if we delete team we will also delete all of the clients connected to that team this could also be for Set n or similar but I like to just say mo Cascade which will delete everything and then we have the name which is just a Char field set the max length to true no 255 I mean and the created at field which was models models. date time field okay maybe we should have a default value here and what I like to do then is to just say Auto now add equals true so what this Auto now add equals true does is that every time we create a new client this field will be automatically created or so filled in by Jango we have one very similar example changed at equals models. dat Time Field Auto Now equals true and the difference between this two is that every time a client is saved this will automatically be updated by Jango to now so that makes it very easy to get track of when a client was created and when it was L saved so I can save this try to run the migration script no changes detected of course not because I forgot to add this to the settings file client let me try again yes and then we can run the server just need to add this here as well so from dot models import client admin. site. register client so let's go to the interface refresh then we have the clients here as well so if I try to create one I first need to select which team I want to use so then I can say client one for team one and save so now I have a client there as well and these are now connected just as you can see here okay and then I want to make it possible to have a too list for each of the clients so let me create one more table to do list icon what should I use here let's just select one that fits very good here ID big in primary key and here I want the reference up to the client so client should be a forign key and I want the name of this to do list so Char field and I want to know who created this so created by is also a forine key maybe we can also have the created head here as well like that so then I need a connection between the created by and the client up to these other database models so I can set to do this dot client points to the client. ID field and the to-do list. created by is the user. ID so if I just close this for now you can see here now that we have a to-do list which is connected to the client which is then again connected to the team which is connected to the user the too list is also created sorry the to-do list is also connected to a user so when we have a to-do list we can easily see which clients this belong to and which team the client belongs to as well so I think I just want to have this to-do list in the same app as the client so at the bottom here we can say class to do list models. model and by the way you will learn more about the models I just want to set up everything here so it will be easier for me to explain how things are connected and more things you can do so here I can say client equals models. forign key client related name is to do lists and on delete models. Cascade so since we have models. Cascade on both of these means that if we delete the team all of the clients will be deleted and then all of the to-do list connected to the clients as well will be deleted so I can copy these three and as you saw we also want a connection to the created at we have uh sorry created by so created by equals models. forign key user related name to do list on delete models. cascate so then I just need to import this here again so from Chango contrib models import user so now it's very easy to get all of the to-do lists user have created and it's easier to get all of the to-do list that's connected to a client so now all of the tables in the database should match what we have here on this app we could also go further here now and create one more table for the tasks but I think you should start to get a little hang of this so what I want to do then is to go back here and add one last table called comments but before I do it I want to add it here as well so let me just change this so I want to have one more table for comment icon comment ID big int and I will show you soon why I want to have this PK and this can have the body or content text field and when it was created and also created by so how should this be connected to anything here I want to make it possible for a to-do list to have comments and I want to make it possible for a client to have comments so up here on the to-do list we can add one more field there called comments and this should be a many to many field and the same can go on the client so just paste it up here and then at the bottom here I can say to do list. comments point this to sorry comments point this to comment do ID and the same with the client client. comments point this to client sorry point this to command. ID so we just close this now you can see here that they have the new table here which is just connected to the comments there and comments there so this isn't actually anything unique it's just very but it's good practice to have a very simple table that can be reused like this because now this isn't really connected to anything and it's not specific to a client or to do list or a theme or anything so all of the table can be reused for all of the other purposes as well so let's set this up in Jango need to add this at the Top PA close comment models. model and here you see that you have the ID which is built in but you can add a Content which is a models. text field and we want to know when it was created and who it was created by so let me just copy these three fields and then we can set this to comments instead so now we have a connection between all of these and it's very easy to get all of the comments that a user have created so if I just import these last or newest tables here to the admin interface we can say import comment and to do list add them here as well admin. site. register comand and admin. site. register too list I'm save we just need to run the make migration script and the migrate script if I run the server again now go back to the admin and refresh you'll see that we have all of this here so if I now create a new to-do list we need to select which client this belongs to to-do list one for client one and team one created by admin and save and we can also add a command command one for to do list one so if I save now this isn't actually connected to this at all this is the only information that we have on this but if I go into the to-do list um okay sorry I forgot to add it to these two here of course so here is the commments equals models. many to many field commment just copy this paste it down there and save now we need to make migrations again migrate run server and refresh and now I can select that this comment should belong to this to-do list okay so I think that I can set this to blank equals true let me try I sometimes forget if that is correct um one un applied and we can have it here because this field shouldn't really be required for something like this so make migrations and my great just want to test sorry I forgot to run it refresh go in here now you can see this is not bold anymore which means that we can deselect this save and now it's not connected anymore okay so now I have set up the base tables here in eraser and as you can see you now probably have a little bit better understanding of how the table can connect to each other using many to many fields and forine keys so now I just want to show you a little bit more fields that you can use for the different data you want to store for example you can have a slug models. slug field and what the slug field is is a URL friendly version of for example the name so if the name is hello world then the slug would be hello Das world so this is now the proper way to store a URL for example for a blog post or a page and similar by the way if you want to learn even more D Jango or view from me you should check out my website Cod within.com the site has many premium courses and a lot of awesome blog posts and for as little as $20 per month you will get access to all of my content and you'll be able to track your progress you can talk to me and similar so go to codit stein.com after the video and sign up you also have things like um buen Fields so for example published mods. buen field this can either be true or false so that's what a bullying field means you either have a true or a false and this can also have an attribute called default set this to true so that when this is created it will be automatically set to true or you can have the default set to false so as you can see here there are multiple different attributes for the fields as well or you can for example have a number of commands equals Smalls do integer field so integr field is a number field so that's one more type of field that Jango has or the image field so image equals models. image field and this usually comes with attribute called upload to example media slash articles so then images that are selected for this one we be uploaded to a folder called media and inside there a folder called articles okay so let's say talk a little bit more about the Char field we have the max length set to 255 this is now a required field let's say that we want to make this um optional for the user to fill out if we want to make it possible for Jango to store empty values in the database for Char fields we can set something called blank equals true so now this will store if you don't fill up this field database will store it as an empty string sometimes or many times people use both blank equals true and null equals true and what this does is that if you try to save now the database will be stored as null so they will have a null value in the database and this isn't the very bad but the problem is if you store this in the database it will be stored as that and if it's empty it can be stored as null so the problem with that is that you can have two different ways to tell Jango that the database field is empty okay so then we can continue to talk a little bit about functions and how to uh how to design models for example if you have this Cent client uh and we go now into the admin interface you can see here that we just say client object one this is the class representation of this model class here what if we want to show the name instead if you want to do that we can say def Str Str self so we create a method called string to override the built-in string method and say return self. name so now we just return this value instead so now you can see client one for team one or you can customize the string if you want that client put in a variable there go back and refresh there you can see here now show the whole string that you see here but usually this is what we want and by the way way for example an override like this is what we want to see as the first functions in a database model um below here we usually have custom models so for example def um number of commands self return self. commands. count so if you now want to know how many uh how many comments that a client has you can just say client. number of comments and this will be returned so this is usually the order we want to have things in a model we have the fields first the built-in functions or overrides and then custom Methods at the bottom um if you want to override for example the default ordering the name and similar we can add something called the class mattera here and say order equals sorry ordering equals I think that is correct now create a list here and say name so now this will be order AO alphabetically let's add one more second save okay that's probably the way it was either way but if you want to reverse this we just minus name now you can see that the default ordering is reversed and this is then the default ordering that will be used in views and similar if for example say client equals client. object. filter or all then this will automatically use this ordering um okay let's just remove this can close that file um other things we can add it to the mattera is that here we can see client which is the plural name for this s the verbos name so verbos name for example here we can say hello so then it will override the name as you can see there and then there hello but this is then the plural name of hello so if you want to override that we can say verbos name plural equals hello like that and overr it like that and usually this is something we do when we for example have a class name category because then D Jango will automatically call the plural name of this categories which is the wrong name to spell way to spell this in English Okay so let's talk a little bit more about the last thing that I usually use the meta for for example if we say Here Close um info table for example this is just a random name I will show you why I do something like this models. model and then in here let me just copy the is two paste it there like that so now here I can say class meta abstract equals true so what this abstract equals true do is that this table will not be added to the database and what's cool about this is that instead of adding this prop down here I can just remove them and post in info table here instead of models. model because this already inherits this but adds these two Fields automatically down here so I can do this for that one I can do it for this one and if I want to do that for the comment as well sorry that was where I was supposed to add it so now all of these three tables are inheriting this and automatically have these fields on it okay this should be abstract let stop and start again yes make migrations so you can see here nothing was changed because this is only something that Chango handles automatically for us but now we don't need to have these two on either of these three tables again so if I wanted to as you can see here we have the name for example this can also be up here if you didn't use it on there and you can also add multiple things up here or functions for example you can have a function that do anything with the date and similar that you don't want to write multiple times okay so the last thing I want to talk about now is the how to override the default save functionality so so I usually have done the client the fields that are for this model The Meta the string representation and built-in overrides and then the def save method so here weos itself the arguments and K works and here can just super and then we call the client model self do save POS in ORS and K ORS again and then in here I can say print saved so now everything of the code that I put here will be run before it's actually saved in the database so if I go back now and go into a client and just click save go back to the terminal you can see here saved so for for example what I can do here is that uh if hello in self. name print hello was in the name and let's say that I don't want people to be able to store hello in the name so I can say self. name equals self name do replace hello with hi instead dead and save so if I now go back and refresh try to create a new client blah blah blah hello blah blah blah save and you can see here instead of storing this as hello there it was stored as high instead because I did this over right typically this is something you can do with replacing HTTP with https and similar Okay so then I just want to do one more thing let's say that I want to have make it possible to choose between things uh for example the status for this client so choices equals and we create something called a tle and in here we create two more tles first I put in the value that I want to store in the database for example um active and then active and archived archived so this is the value that will be stored in the database and this is the value that we will see in the admin interface and other forms that we print this here so status equals mods. Char field max length set to 255 now have a new uh now have a new attribute called choices equals choices like that so I want to make it possible to specify a default so either I can say default equals active but that is a little bit dumb because if here was a typo simp something similar then this wouldn't work so what I like to do here is to say active equals active and then use this variable down here instead and then down here I can also say active so this will just point up to this which points to this string again and the same goes with archived archived archived like that so let's save and see what this looks like in the admin interface face migrate and run server so if I now go back and refresh go into client you can see here that I can select between these two and this was automatically selected by Jango nice and that was everything that I want to talk about in this video if you have any questions or things you want to learn more about for Jango models feel free to leave a comment below and I will answer as soon as I can see you in the next video
Info
Channel: Code With Stein
Views: 8,624
Rating: undefined out of 5
Keywords: code with stein, django, learn django, django tutorial
Id: RbJOmgTX63M
Channel Id: undefined
Length: 39min 19sec (2359 seconds)
Published: Mon Dec 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.