Django Rest Framework API #22 / Many To Many Relationship , Nested Data

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone in this tutorial we are going to discuss the many-to-many relationship and in order to understand the many-to-many relationship let's compare it with the many to one relationship which i made a video about previously and i will leave link in the description for that video and for now let's see some graphical explanation that will help us understand the many-to-many relationship so in the many-to-one relationship we can link multiple objects of a model one to one object of a model two but each object of a model one can be linked to only one object of a model two at the time for example a post can have multiple comments linked to it but each comment can be linked to only one post at the time using the many to one relationship while with the many-to-many relationship we can link multiple objects of model 1 with multiple objects of model 2. an example for that is a school system where you will link students with the modules that they are studying so to implement the money to menu relationship in our api let's create a new app and name it school and start first let's activate the virtual environment and then let's navigate to our project folder my api and inside here let's run python manage dot by start app and let's name it score and as you see here we have the school folder available with the files inside it so let's go to model models.pi and inside here i want to create two models first model is modules which what the students will be studying so let's name it modules or you can image module it's fine and inside here i'll have three fields first one is the module name so i can say module name and it's going to be a character field with max length um i think 50 will be okay and the second one will be the module duration okay so in months for example how long this module takes how much time was allocated to this module and let's have it as an integer or integer field and the second one will have our third field will be the classroom okay so let's have a class room and it will be also a number referring to the classroom and let's return the name of the module so then str method let's return the name so this is the first model that we need the second model that i would like to create is student so let's have it student you can name it student students whatever let's name it students because we already said modules there so okay sounds better and inside here we're gonna have the name which is the student's name and the correct field the max length of i think yeah 50 is enough as well and second field will be the age and it's an integer third field will be the grade and it's an integer as well and the last field is the field that we need to use to link the modules model with the students model using the many-to-many relationship so we can simply say modules equal models dot many-to-many fields and inside here we just specify which model we need to link to which is the modules and let's return the name of the student and now as you see the models are ready so let's save this and let's go to the admin the pi and add these models there so we can see them in the admin panel so let's import import them first we need to import the modules and students okay and then we register them register the first one the modules and then we register second one to the student okay let's save that and now let's add the new app that we created to our installed app so our api can acknowledge that and it's right here is cool and save it and then now we should run the migrations so python by make migrations first and as you see here we have done two migrations the modules and the students and then now we can run the migrate and now the migration is done so in order to see this in our admin panel let's just run the server now and let's go to the browser and refresh and as you see here we have two we have our app here the school and we have the two models that we created so if we go to the first one and let's create some modules here for example let's start by for example math and let's say four months the duration classroom number one and let's save it and let's add another one which is um physics for example physics and it's also four months classroom two and one more let's for example add the history and duration three months for example and classroom four and now if we go add a new student to our database basically we can add the name let's say for example allen at the ages 18 grade 12 and this is the interesting part as you see here we have three options which are the modules that we created and as you remember in the many-to-one relationship we used to have here one option okay so we we could create add one field only but in this case with the many-to-many relationship i can add all the the modules that i've created link them to the uh to this particular student so i can just mark them all using control and you know choosing one by one or command if you're using a mac and then i can simply save and if i open this again i'll see that it's saved and i have three modules linked to this user and i can add another student for example let me go back to students i can head another student for example mark and then age of 17 grade 11 and then i can choose that for example mark is not doing math is doing history and physics only and then i can save it and now i have two students with different modules linked to them and now let's create the necessary files that will allow us to access the school app from a custom endpoints so let's go back to this code and inside the school app i'm going to create a new folder and name it api inside here i'm going to create three files the first one is the serializer dot pi and the second one will be views and the third one will be urls and let's start with the serializer pi and first we need to import the serializer from rest framework so let's type it out serializers and then we need to import the models from our models.pi file and there are modules modules students and now let's create two serializers one for the modules and one for the students so let's create a class and name it modules serializer and it's gonna inherit from serializers.model serializer and inside here let's specify or add the class matter and let's add the model name which is modules and the fields which are um id because we need to get the the object's id and let me check the model so we have module name module duration classroom so we need to add that so here module name and then module duration and then classroom okay and let's create second class and it's student serializer and it's going to take same thing the model serializer and let's first specify the class meta the model name will be students and fields will be the id name age and great and the last one is the modules okay i think that's it let's check the model so let's name age grade modules and i'm going to get here depth equal one to get the nested data okay so let's save this and the second thing we need to do is to add uh the views classes inside views.pi so let's go to views.pi file inside here we need to add two classes one is for the students and one for the modules and we will use a model view set so i'm going to copy paste the code here just to be more efficient and save time because it's just a symbol code so we're importing the view set and then the response and then after that we're importing the models that we need to use and then which is the student students model and the modules model and then we're importing the serializers from the serializer.pi file in order to use them inside our views to serialize the data and then we create the views classes so first class or first view will be there students view set and it's a model view set we specify the serializer that we need to use which is a student serializer and then we add a normal git query set method which will take all the objects from the students and then send them back to us okay okay so the second thing or the second class is the modules you can just simply paste here and then just edit it so it's the modules view set and the serializer will be modules serializer and inside here we can just type module and we get query set from the modules model and module here so basically that's it for the for now for the views dot pi let's save it and now let's create the end points for the school app inside urls.pi and again i'm going to paste the code here because pretty simple and here we're using rest framework routers to specify or add the two endpoints that we need and allocate a view set for each endpoint so as you see here we're registering a student as an endpoint with the student view set in module with the module view set and then we including them inside the url pattern so let's save this and then let's go to the main project urls.pi file and then include the endpoints that we created inside the school app inside the project urls dot by file so to do that let's copy this and then here we can initiate the end point or start the end point with the school referring to the app and then we replace the posts with the school which refers to a school app so here all the the urls or endpoints inside your dot pi will be included so let's save this file now and check that and i'm getting this arrow here that says cannot import uh name student serializer because i think i misspelled it so let's see serializer.pi file and i can see here i forgot to put an s so let's save this and what for the server to rerun and our server now is running and now it's the time to test the endpoints so i'm gonna run postman here and i'm gonna perform a get request to the student endpoint so i'm going to type here school slash student then i'll send the request and as you see here in the json data i'm getting back the two student that we added in our database using the admin panel allen and mark and then also i'm getting as a nested data here inside the student object the modules that each student is taking so that's pretty good and now i can also request a specific student by just adding its id as you see there and then perform a git request and now i'm getting uh only allen or i can get mark as well so by changing the id so i'm getting the other student and the next thing we need to do is to handle the post request in order to do that first let's add a json object here to represent the new student that we need to add to our database okay and for that i'm just gonna copy this here this object and just do some modifications so we don't need the id we'll add a new name for example john and then let's say john is 16 and he's in grade 10 and for the modules i just need to add an array of objects that represents the name of the module only okay so what i'm going to do is i'm going to remove the extra data here okay i'm just leaving the name of the module because we will need to query using this name so this is this basically the data let's edit the url this is the object that we need to add or the new student that we need to add with the modules that will be allocated to the student and now if we perform a post request i get the user object back which means the user or the new user has been created and saved in our database but if you look here no modules have been added and to solve this problem we need to override the create function inside our view so let's do that so we go to views.pi inside here we need to add the create function so let's define the create function and add the arguments that we need and inside here first thing first we need to extract the data from the requests so let's say data equal request dot data okay and after that we need to create a new student so let's say new student equal student the mod the model name dot objects dot create and inside here we need to add the fields so if we look at the model here we need name age grade and modules so let's start by adding them name equal data and we give the key name and then after that age equal data and we give the age we do the same thing for the grade and this will be enough to save the student so let's do new student dot save so now that we saved the student we need to add the modules that we received from our post request to this particular user and in order to do that we need to loop through the list of the modules list and then add each object that's represented by that by that by the module name inside this list to this user so to do that we say for example for module and data modules and that refers to this here so this will give us back the list what we'll do now we'll grab the module object from the database so we'll say module object for example equal modules uh let me just make sure i'm using the right name yeah okay so modules dot objects dot get and inside here we'll use the module name name equal module which is this one and we'll add the key module name so what we did is we we looped through this list and for each object inside this list we grabbed the value associated to the module name module name key so now after we get the object we need to add it to the new student object so how we do that we simply say new student dot field modules dot add and then we add the module object so this for loop will go through each object inside the module list and edit add the the module object associated to that module name to this new student and when that's done we need to serialize the the data type serializer equal student serializer and then we add the new student and then we send or we return response with the serialized data so serializer the data and that should do it so let's save it and let's go test this view inside our postman so i'm going to just change here [Music] the name for example make it steve and leave the rest as it is and then now i'll perform the post request and as you see i got the new student object plus the modules associated to that student or allocated to that student so that's it guys for the many to many relationship so we saw what's the difference between the many-to-many relationship and the many-to-one relationship we uh implemented uh the many-to-many relationship in a practical example and we saw how we can perform a get and a post request to handle the data and in the next tutorial we'll be talking about the update method how to override it in order to get our data updated so if you're looking forward for more content like this please like and subscribe and until the next one
Info
Channel: Code Environment
Views: 9,661
Rating: undefined out of 5
Keywords:
Id: NCBxyw6rDds
Channel Id: undefined
Length: 31min 20sec (1880 seconds)
Published: Thu Oct 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.