Understanding Django Model Relationships

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in say anything from pretty pretty here in today's video I'll be talking about relationships in Django models so this is a video from one of my free courses called django database essential so it's also part of my premium course they share the same videos in this section this is actually a combination of four videos and hopefully after watching this you'll have a better understanding of how our relationships work in django models so if you have any questions about this video feel free to leave a comment in the comment section below if you liked this video please give me a thumbs up and I hope you enjoy Thanks okay so an important part about working with relational databases is having an actual relationship between two or more tables so the first of the two relationships that we'll talk about is the parent-child relationship also known as either a one-to-many relationship or a mini someone it just depends on who is talking about it but basically it's a parent-child relationship so you have a table that represents a parent and a parent can have many children but each child can only have one parent so I'm going to create two tables and each will represent either a parent or a child and from the names it should be pretty obvious so the first table is going to be a language table and then the second table is going to be a framework table and by language and framework I simply mean a programming language and a programming framework so as you know a single language can have multiple frameworks but a framework is just written in one language so an example would be django django is written in python but python has many different frameworks available web frameworks that is so django flask web pi bottle sanic and so on so with this language is the parent and framework as a child so what I'm going to do is I'm going to create a column on each table just to hold the name so models char field and just set the max length to ten I know it'd be exactly the same on each table and then I need to add a foreign key field now you can put the foreign key on either table but it makes more sense conceptually to put it on a child because the child only has one parent so it's a little easy to think about it that way so on framework I'm going to put the foreign key here and I'm going to name it after the parent table so it's just simply language if you were doing this directly in sequel you probably have something like language ID but our for our purposes language works just fine so now I want to create a foreign key which means that this column or this field will reference another table so foreign key I need to pass in that other table in this case the class language and then I need to specify what happens on deletes so now only on date but on delete and then models cascade and basically what this means is if you delete the parent and it will automatically delete all the children for you there are other options that you can do but it's a little more advanced sequel so if you understand that then look up the documentation to see the other options on what you can do on delete so those are the only things I needed to do to at the relationship between the language table in the framework table so I need to make the migrations of course so let me exit out of this and then make the migrations and then I need to migrate okay so now let's take a look at our table so I'm looking for example framework and example language so here in example language I have two columns ID in name and then in example framework I have three columns I have ID name and language ID note that language ID is not the name that I have here it's simply language Django went ahead and added that ID for me because it makes sense that this column is going to hold a language ID so now to create data let me start up my shell again and from it's the example dot models imports language and framework okay so the first thing I need to do is create a language so I'll call this one Python language name is Python and I'll save that to the database and then for frameworks I'll create so I'll create a Django framework and I'll create a flask framework but note how I didn't specify the language for each framework so to do that I'm not passing in a literal value so it's not like I'm saying you know framework or a language is equal to Python directly it's not like this where I say frame work and then language equals Python I can't do that but I can actually do something that's pretty similar the only difference is instead of passing in a string I'm going to pass in the actual object of the parent that I'm interested in so I have Python here this is my language object so if I pass that to the language field so Django dot language equals Python in flask dot language equals Python I could have instantiated that way as well so name equals let's create another one so bottle equals framework and then name equals bottle and language equals Python and then I'll just save all three of those and then let's take a look at the database so now looking at the Framework table I have three IDs so one two and three I have the three names Django flask and bottle and then for the language ID they all are number one and this number one represents the ID of a row in the other table that's a parent so if I go over to the parent table which is language we see that Python has the number one if I do another combination of languages and frameworks so let's say Java Java language name equals Java and then say spring equals framework and then name equals spring and then the framework excuse me the language is going to be Java and I'll just save both of those and the reason why this one failed is because I try to I added Java to spring before I save Java so every time I save an ID is generated but because I added the language Java before I saved it there was no ID generated and that's what it's complaining about there's not no constraint as saying there's no language ID so if I just create that again so framework name equals spring and then language equals Java it should work this time and it does okay so if i refresh this one I see I have Java as the second language so ID of number two and if I go back to the framework here I see I have a fourth row here and instead of having the language ID as one the language ID is now 2 which represents Java so with this I can now query my database for frameworks that are in a particular language or I can go the other way I can say give me all of the frameworks that are available for a certain language so that's what I'll show you how to do next to query these relationships you'll find that Django does a lot to help you out with this so to demonstrate the first thing I'll do is I'll create the stir just so we can see the results when I return them so it's just going to return the name for both and then I'll go back to the shell and actually restart it so I can get those updated names so from example models import language and framework okay so I have that so let's start with the child so I want to query the framework table and I want some kind of filter on it so first let's just look at all just to see that everything is there and I put a uppercase L but we see that I have four frameworks so now I want to look for frameworks with a particular parent so framework objects a filter so to do this as you can imagine I'll do something with the language because that references the parent so language and then once I do that the cool thing that is Django does for you is because this is in a relationship it allows me to reference columns in the parent so by looking at language Django knows that the language is the parent so if I do underscore underscore I can now have access to columns in the parent and I can filter on those so now instead of looking at the columns here I'm looking at the columns in the other table so in this case I only have names so I'll look at the name and then I can look for Python so this is the parent table and then this is a field in the parent table and then this is the name that I'm actually looking for so when I do this I get Django flask and bottle if I change the name to Java then I just get spring and of course I can use the same field lookups that I had before so instead of just using name equals I can do something like name starts with and then I can pass in pi and I didn't put double underscore so just keep that in mind it's really easy to mess up because you can't see it that well but anyway make sure it's double underscore otherwise you get a long error like that and you see it gives me Jango flask and bottle again because Python starts with PI if I just use P let's say PA I get nothing because there is no language that starts with PA so it's very straightforward going from a child to a parent but what if you want to go the other direction what if you wants to start with the language which is the parents and then query for the children or query something in the children well it's actually pretty similar so I don't have a field called framework here but Jango will just take the name of the models so framework and use the lowercase version so if I use framework like that then the process is the same so double underscore and then I can reference fields inside of the class so name and let's say spring and this will give me the language Java so basically this query is saying give me a language where the framework is where it has a framework name spring so if I change the framework to bottle it's going to give me Python because python has a framework name bottle among the others which are Jango and flask so as you can see the queries here are pretty simple and like I said just add the extra part with double underscores if you want to have a different type of filter so you can have like is no you can have exact you can have I exact you can have contains all of the ones that we cover before are valid here just know that you start with the name of the parent or a child then you use one of the fields inside of that table and then you can use one of the additional lookups so pretty straightforward using parents and child relationships in Jango and next we'll cover how to do many many relationships where it's not quite a parent-child relationship because one table can have multiple elements of the other and the other table can have multiple elements of the first table and I'll explain more about that in the next video the other type of relationship that I want to talk about is a mini two mini early basically a type of table can have multiple instances that are related to another type of table and the same thing in Reverse so an example would be movies and characters in those movies and those are the examples that I'll use right now so let's say we're talking about superhero movies so Captain America is a character and Captain America is in several movies so Captain America is in the Avengers movies he's in the Captain America movies and he has made cameos and let's see the Thor movie one of the Thor movies but you can also go in Reverse so you can think about one movie in particular like The Avengers and then you can say there are multiple characters in that movies so you have Captain America you have Iron Man you have Thor you have the Hulk and so on so there is a mini-sub mini relationship with those it's not a strict parent-child relationship because it's not like one character can only be in one movie or one movie can only have one character it's there's no limit to the possibilities so that's the example that I'll create here so I'll create a class called movie and I'll create just a simple column called name again and I will return the name as the string representation and then I'll have a character one as well and that should be model and then name models char field and then max length is going to be ten again and then finally I'll do the same thing return the name as a string okay so as you can imagine I have to put some kind of field somewhere to relate these two tables together and that field is going to be a mini two mini field now when it comes to creating these mini so mini fields you can put it on either table but you want to put it on the one that conceptually it's kind of you know a lower level so a movie is something that is on a higher level than a character is the way that I will put it so movies are more important the characters of course a movie has characters and characters belong to a particular movie but when you think about the relationship between the two the movie has a higher status between the two so I'll put it on the lower one which is the character so for this I'll name this movies and it's going to be models dot Minnie - Minnie field and I'll pass in the other table so in this case movie so now when I run this I need to make migrations first and then I need to migrate and now let's take a look at the database so movie and character are the two tables that I created so if I go to example movie I see ID and name and if I go to example language I see or excuse me example character I should say I see ID a name well how this is working because there's no third column anywhere like there was when I was looking at their framework there's no movie ID column and there's no character ID column and the reason why there isn't a column like that is because there just can't be because each movie can have multiple characters and each character can belong to multiple movies so what happens is a third table is created and it's kind of a combination in the terms of the name of the two models so in this case it's called character movies so it's going to relate a character ID in a movie ID and the combination of the two represents like a character being in a certain movie so to illustrate that what I'll do is I'll start at my shell and then I'll import those and then I'll create first a movie so let's say Avengers is the name of the movie and then I'll save that and then I'll create a character so Captain America and I also save Captain America so if I look at this table nothing happens because I haven't actually related them yet but if I look at character I see Captain America is there and if I see the movie table I see Avengers is there so now I want to relate them so remember where I put the field I put it on the character so a character belongs to a certain movie so what I'm going to do is I'm going to say Captain America so this is the object that represents the role for Captain America and then I'm going to reference the movies and then finally I'm going to add one more thing and that is add so basically add a movie for Captain America and I'm going to pass in Avengers and then once I do that if I take a look at the character movies table now I have some data in here so the ID of the row is 1 but the character ID is 1 and the movie ID is 1 that means the character ID Captain America is in and the movie ID of 1 which is Avengers so if I add more movies and characters let's say Civil War and then I'll add another movie let's say Thor I don't want to use the were so let's say the word dark world I think that's a little bit better because the name of the characters Thor as well so then I'll create a Thor character so this will be character name equals Thor and then I'll create a I'll leave it at that so I created the Civil War movie so I can add that to Captain America so Captain America and let me save all these firsts so Civil War save Thor save and Thor character save now let me add Civil War to Captain America so captain underscore of America movies add Civil War and then for the Thor character movies add Avengers and Thor and now if I take a look at the table I have more data so now it's telling me character ID 1 which remember is Captain America is in if I go back to the movies character ID 1 is also a movie ib2 so if I look at the character or the movie table number two is Civil War so I'll Captain America's in that and number three is Thor dark world so if I look at the character movies again character ID to a store Thor is in the Avengers which is the ID 1 and Thor is in Thor dark world the movie so number 3 so you can see how things are being related here I mean if I wanted to add them or if I wanted to create this relationship directly all in one go I can do something like this so if I want to create a new movie that Captain America is in instead of doing movies add I can do movies crate which instead of passing in an existing movie object I can just create one right here so if I create name what's another movie Captain America has been in Winter Soldier it returns a movie Winter Soldier for me and then if I look here I see the movie ID for character one is in which is Captain America and if I go to movie here I see number four Winter Soldier has been created so as you can see is pretty simple to use many to many relationships in Django in the next video I'll talk about how to actually query these query many so many relationships is pretty similar to querying one-to-many relationships so as an example if I want to search for a character I can say character object's filter and then what I want to do is I want to specify that Minnie - Minnie field so movies and then underscore underscore and then I can reference fields and the other table movies so if I say name equals Civil War that will give me Captain America because Captain America is in Civil War so if I go the other direction if I say movie objects filter I don't have an explicit to feel to on movie but if I take the other class and put the lowercase version of it so character with the lowercase C then I Karev a field inside of it and I can say Captain America and this will give me all the movies that Captain America is in so Avengers Civil War and Winter Soldier so if I wanted to see all of the other parts of the relationship for a particular object so by that I mean let's say I get one movie so Captain America or one character character objects filter name equals Captain America and this should be gets instead of filter because I just want one so if I look at Captain America here I see this as the character Captain America and if I want to know all of the movies that Captain America is in I can do Captain America so this is the actual object the row and then reference that field so movies the mini to Minnifield and then I can just type dot all and I will give me all the movies that Captain America is in and then I can kind of do something in Reverse so if I want to know all of the characters in a particular movie I can first get a movie so let's let's have this movie be the Avengers so Avengers is going to be equal to movie objects gets name equals Avengers so we see here it's the Avengers so there is no field in Avengers for you know characters so what Jango does is it takes the name of the class so character lowercase version then you can app in underscore set and then you can get everything and then that tells me all of the characters that are in the Avengers movie at least all the characters that I have set up in my database of course there are boar characters are not in the actual movie so as you can see like I said working with meaning to many fields is pretty easy the relationships are pretty easy to understand and you can get a lot of mileage out of using this in your database because really that's the main point of having a relationship database is you have a relationships between multiple tables and the minutes one field and the meaning to mini field or I should say the foreign key field and the mini to Minnifield allow you to do that in Jango
Info
Channel: Pretty Printed
Views: 69,723
Rating: undefined out of 5
Keywords: django model relationships, django models, django model relationship tutorial, query django relationship, django, python, tutorial, programming
Id: 2KqhBkMv7aM
Channel Id: undefined
Length: 25min 56sec (1556 seconds)
Published: Thu Jan 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.