14. Foreign Keys – Django by Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello world Noah here welcome to the next episode of Django by example in this episode we're going to create a new model that represents a category in our database and then we're going to look at how to use foreign keys to link categories and items so essentially what our goal is is we're going to be able to categorize these items in our database so if you take a look at our home page some of these things are programming languages like Java Python and C++ and some of them are IDE s like eclipse and pycharm and we could add even more we could add famous programmers to here we could add I don't know computers if you wanted to there's lots of different things that we could do and we want to be able to keep things nice and organized so in order to accomplish that we're going to have a category model and we're going to define a couple of different categories and then for each category we can link a bunch of different models there are a bunch of different items to it this video is going to be kind of long and maybe a little bit confusing so definitely make sure to pay attention the first thing we're going to do is actually create the model itself we're going to create the item calls we're going to create a class called category and it is of course going to inherit from model shop model exactly like we did before and model or category is only going to need one thing the name of the category this is going to be a char field which again is just like some text and we'll set the max length to be 32 so essentially again we have category which represents a category of items in our database and it has one thing one not piece of data which is name and name is just some text and we'll go ahead and implement the string method which will return self name so basically if you want a string representation of a category it's just whatever the name of it is very simple what we'll do is we'll actually get this into the admin and add some categories and then we're going to talk about how to link items to categories so let's go ahead and do tools and we need to run a managed py task hopefully you remember this from the video when we made the item model but every time you make or modify a model you need to call make migrations you can see it created a model called category and then you need to call migrate and that will actually apply the migration so now the database has been updated a new table has called category has been created and we can now store categories in our database the last step that we need to do is go to the admin and actually register it so admin dot site got register and category that's what we called it and we just need to import category from models so I just added that import right there so that is pretty much all we need to set it up we created the model and we registered it so we can now go to the admin page looks the server is oh it's not running let's make it run and there we go so you can now see categories shows off let's quickly fix the pluralization because that doesn't look very good to do this you need to define a class called meta maeda I don't know whatever you want to call it inside of the model and you just need to define for both on your score name underscore plural so we'll set it equal to categories I wish I could spell so we just have this class called meta inside of this class and verbose name plural is equal to categories and that fixes that issue so it now has the proper pluralization not a huge issue but I think we kind of want to make it look nice so let's go ahead and add two categories we're going to add a category called programming languages and we're going to add a category called IDE so there are now two categories programming languages and IDE now we're going to need a way to link specific items to specific categories and the way that we do that is by a foreign key a foreign key basically sets up relationship from one row in the database to another or another way of thinking about it is one instance of a model to another instance of another model or it could be the same model well let's take a look at how to do that we're going to add a category which is going to be another value for item and we're going to use models foreign key and we need to specify what the key is for and in this case it's for category so we're creating a new piece of data we already had name and description but we're creating a new piece of data called category and category is going to be equal to model foreign key so it's going to be a foreign key to category it's basically going to be a reference to a category somewhere okay that's really all it takes there so of course since we modified a database from since we modified a model we need to do make migrations and migrate so we'll go ahead and do run minus py tasks and we need to call make migrations but it doesn't quite go through perfect at this time because it says you're trying to add a new field called category but there's no default value because what happens is we already have these five items and if we're trying to add a new piece of data in this case category we need to give all of these items a category to begin so we'll just go nice and and easy and we'll set them all to be category with ID 0 and then we can you know change them manually again this only applies to items that already exist so these 5 items but if I add a new item it will have nothing to do with what we're doing here so don't be confused by that so let's provide a default for now um and I think we need to import the we need to import the model from PDB on our scrap import category no not ok so maybe we don't need to it shouldn't just be category a dot objects get ID equals one name categories are defined um maybe just put one in there and then let's try migrate okay so I was actually a lot simpler than I thought so basically we need to give some sort of value for the items that already exist so in this case we're just going to set them to be one for whatever I guess in that case it would be programming languages and so you can see we added a new field called category to the item model and then we call migrate and it successfully applied that migration so if I go to look at a particular item you'll now see that there is a section called category and if I look at this it's a drop-down menu that displays all of the category values again if a foreign key so it references another model again we have these two categories here so those are the two options now all we need to do here is go to eclipse and change this to be iges it saves and then go to pycharm and change that to be iges and hit save so now each of these items has a category associated with it and if I were to add a new item I would pick a category that I want to associate with it so let's go back to the home page and let's make it so that when I go to Java for example it will tell me what categories so it'll actually say programming languages or if I click on eclipse it will say iges so to do this we'll go to the item right here and if the item is not none so if it does indeed exist right under the name will view may be an h4 so it's a little smaller we just need to say item category because once again we made category which is a value and so this will reference another category so we could do item category to get the category of the item and then we can do dot name so item that category will give us the category and once we have it we can get the name of that category by using dot name and if i refresh you'll see it says programming languages if I click on Eclipse you'll see it says IDE Python programming languages of course so on and so forth so it's very very simple to see how you can get a get from from math side basically if you have a an item you can get the category associated with it very simple but there's actually a reverse relationship so if every uh if every item has a category then every category must have a list of items that goes along with it and indeed Python audit is using Django automatically sets up this reverse relationship for you I'll show you what it looks like in actual like in Django so you can see it with the you know completion and all of that if we go what we're going to do is we're going to we're going to be modifying the index so that instead of getting all of the items we're going to get all of the categories and then for each category we're going to list all of the items that belong to it so just to show you really quick if we do let's just grab a category subscribe like that so you'll notice that something is our a is defined for us something called item underscore set an item underscore set is a query set or basically like a list sort of of all of the items that correspond to that category so in this example we get the category whose ID is one which is programming languages and when we use item set that gives us all of the items for that particular category and just like before with item and objects at all we can get the item set and when you dot all to get all of the items associated with that category so essentially what our plan is is to loop through all of the categories and then for each category we're going to loop through all of the items that belong to that category and that will allow us to organize this index page that it looks a little bit nicer so how are we going to do that instead of passing all of the items we instead want to pass all of the categories so categories is equal to category down objects all so we're going to get all the categories then let's comment this out you can do command slash or for commenting or basically anything with a curly brace and a pound sign will be considered a comment by Django and it will be ignored but we want to do for category in categories just like what we had with items but it's a different context variable this time and for each category we want to print out the name of the category which we defined here and then we want to loop through all the items associated with it so we're going to use and nested for word for item in and given a category we can get its item set which is all of the items that are associated with it and then we just type dot all you don't need to type current parentheses and in fact it'll give you an error if you do but you just say dot all and it will automatically call that method for you and then inside of here we want to bring back this line right here so let's just look at this for a second before we see what what it actually looks like so for each category in all of the categories in the database we want to display the category title and then for each item in that category for each item that is marked for that category we want to put a link to it this is really the key part we basically say we have a category we use the reverse relationship to get all of the items that belong to that category and then we say dot all to get all of them and so we can use a for-loop with this and we just put a link to each one I'm going to put a line break after the for loop just to keep everything separate and let's see what it looks like there it is very nice so essentially you can taste those programming languages then Java Python C++ IDE s Eclipse PyCharm so it looks a lot nicer now because basically everything is organized by category instead of just having a ton of length all in one place and of course if I change I'll show you really quickly if we go back to the admin page if I change one of these items let's say that I make C++ an IDE obviously that's not true but if I change it you'll notice that it drops over here it's no longer in the programming languages section it's now in the IDE section because I marked that it's an IDE and so the reverse relationship says everything marked with an IDE would include C++ I'm going to change it back because of course it belongs to the programming language and if i refresh you'll notice it goes back where it was before okay so that's pretty much it for this video we learned how to use a foreign key to define a relationship between two different models and then we also learned both relationship sides we learned how if you're given an item you can get the programming language alright if you're given an item you can get the category that is related to it or if you're given a category you can get a you can get all of the items that are marked with that category we have now achieved what we set out to do in the beginning we've built the exact same website pretty much that I showed off in the introduction episode of course there's so much more to Django than just this and the series will continue there's other stuff that we want to look at some things include how to use static files so that we can actually add some styles to this website and make it look a little bit nicer than just plain HTML we can take a look at media for image uploads so basically you could have 38 an image with with each of these items and have it show up on your page we can look at how to use users because Django has awesome support built in for user accounts we can learn how to deal with that we can learn about many too many fields so for example a user could have the ability to favorite all of the their favorite programming languages an IDE s and other items and they could see a personalized list of their top favorite things there's all kinds of different things and then eventually we'll actually talk about how to deploy this on a website so that you could show it to other people and actually make it live on the internet for anyone to see so I hope you've enjoyed everything up to this point as always subscribe if you want to see more comment with what you want to do with this website I have a lot of ideas but I'm always looking for more in fact this video click the like button I'll see you guys soon with some more Gengo bye for now
Info
Channel: Noah Rubin
Views: 37,593
Rating: undefined out of 5
Keywords: django, web, framework, python, python2, python3, flask, backend, frontend, html, css, javascript, model, view, controller, mvc
Id: 6lafzyjiqgQ
Channel Id: undefined
Length: 16min 23sec (983 seconds)
Published: Sun Mar 19 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.