Python Django Inheritance Optimisation Exercise

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is a common scenario you have a table here in this case it's a product table from an e-commerce store in this scenario i'm just recording information about books that i'm selling in my store so naturally i'd have here fields related to things i want to store about the book so the title the price the number of pages and so on maybe over time or i know initially when i'm designing the database that i also want to sell other products for example cupboards for the books so at this point i have a number of choices to make because for example if i were just to extend the table and now include fields related to the cupboards i want to sell so for example the number of shelves the height and the book so i want to record information about that in my products table i now have a problem this problem might not seem obvious but take for example we start to now add data to our table we start to add the book data so the category title price number of pages images created update but then we have other fields here which will now be empty of course it's the same problem now if we want to store our cupboards inside the products table so for example here the number of the pages isn't applicable to a cupboard therefore we start to have null value fields so when i talk about null values sorry i just mean empty values in the table so sometimes null values can mean different things so the main point here is that when designing tables where in this case for example a product we enter into this table we'll have empty fields is negatively viewed from the perspective of database normalization so the question is set how do we design a product table for many kinds of products where each product will have different fields so that we can avoid any empty values in our table a very warm welcome back to the django rm series in this tutorial we focus on extensible data modeling utilizing the django orm so in this tutorial i'm going to take you through four solutions for django solutions that potentially is going to resolve our problem once i've discussed the first solution we'll then give you some examples of solution two three and four so we can actually have a look to see the the performance and how you'd actually implement it within your application solution one concrete classes so if we think back to our original class or original table we had one table and we had lots of fields related to multiple products in that table so the first solution here then is just to simply create a new table for every single product i suppose the technical term here is that we're representing a hierarchy of classes with a set of tables every table will contain all the fields that are related to the corresponding class so i'm not going to show you an example of this because this is simply just building a table which i'm sure you're able to do so let's just think about some of the benefits and drawbacks of this solution so like everything i do i try to avoid telling you what is the best way because there is no single best way for anything because this is always going to be dependent upon the type of project in this case the amount of data that you want to save and serve and query on that's going to be important and then of course there's a whole host of other parameters which need to be considered before you select your approach so i'm just taking you through the approaches and thinking about some of the advantages and disadvantages of each the concrete class or concrete classes the advantages in this case are they are very self-sufficient we have a single table nice and easy to maintain potentially and of course one of the benefits of having this or utilizing this type of pattern particularly if we're for example building a package for others to implement or integrate within their applications this is a very simple table to integrate within just about any application it's a single table it's self-sufficient um it should work in that instance another point to note is of course it's a single table so potentially it's nice and fast to run single queries on having a look at some of the disadvantages of concrete classes the first is the field definition duplication so imagine having 10 tables we would have very similar fields in all of those tables that would be duplicated throughout those tables so category title price image so that could be quite vast amount of data that we're storing or vast amount of fields that we're duplicating sorry over these tables and that could be perceived as a disadvantage the second is the nature of how we're going to be able to query data in all of these tables because we don't really have any pattern in terms of a hierarchical structure of tables that might be synonymous to building database schemas and how we kind of access data through the root class maybe of a hierarchical structure in order to get data from different subclasses here we've got single tables that aren't connected in any way so we would potentially have to run multiple queries or extensive amount of queries in order to achieve the data that we want to collect this approach potentially is very costly then at returning data from the tables next up we have solution 2 which is the multi-table inheritance so i'm going to take you through a quick overview of this and then have a look at a django example and then just go through how to explore or how to start exploring the query performance model inheritance in django works almost identically to the way normal class inheritance works in python so here django will create a a separate table for both the child models and also the parent so here's the example again from the start these the problem here we've got the product table but this time we've got the generic fields inside of the product table now this is the parent table now what we do here is we create child models or child tables and here we have for example cupboard and book and that allows us to add the specific fields we want to include for to model inside of these different classes here so for book we want to store pages etc etc and then for cupboard we want to store height and width and so on so we're going to create in this case with this pattern we're going to create three tables the product table cupboard table and book table so take a look at the example repository you'll find the store and models and you can see here we've got the product model which is subclassing models.model and here we've got the book and the cupboard which isn't subclassing the models model so be careful of that this is how it needs to be set up so you can see the reference there to product and now we've got this set up you can go ahead and migrate so let's go ahead and do that let's make migrations and migrate so let's have a look at the actual table now so if i go into my extensions here don't forget that i'm running um i've got sql sql sqlite there we go let's just make sure we've got it turned on yep so i'm running sqlite or sqlite uh this is an application or sorry a extension that will allow me to view the default django sqlite database i can right click and open the database it's going to appear at the bottom here so i can go in and have a look here so you can see that we've clearly created three models as i previously stated so we've got the book and the product and the cupboard model now created or table created so if we look inside of these tables what django is doing automatically is it's building a one to one field automatically back to the parent model which is obviously the product model and that's the same here in the cupboard so what i'm going to do with these three examples is in the view i'm just going to generate for the home page all the products from those tables so i'm just going to go ahead and assume you can do this i'm just going to create a new super user and add some products to my tables so go ahead and create cpu user no email password admin admin and so on okay so we're going to need to set up the admin area for this so i've gone ahead and in the admin here i've just added some placeholders almost here and if you want to extend this for the product book and cupboard at the same time just registering those tables so we can have a look at them or the default behavior in the admin area now before we go into the admin area i need to tell you that this has been set up with the django debug toolbar so this is already if you download the repository it's already set up for you um but if you want to set it up you just need to pip install the django uh debug toolbar and then you'll need to go into your core and settings at the bottom i've got the dual toolbar panel set and also the internal eyepiece so that's two things you need to do then further up you'll need to add in the middleware so just be careful where you place that middleware it's uh just here in my case and i've also then added the debug toolbar so debug toolbar into the installed apps the middleware uh here middleware here and at the bottom here i've got the ipa internal ip and the debug toolbar panels so once you've done that head over to the urls and you'll need to just import that in and then also just add in the urls and you'll be good to go so one of the things here that's going to be slightly different because we have this tool on is that when you or before coming to the actual admin area you're going to be asked so let's see if i can just simulate this very quickly for you you're going to be asked or uh the toolbar is going to see that you're trying to access the admin area just click on the link and then just click on the link again and that just eventually will take you to the administration so now we set up the three tables in the admin area let's just look at the default behavior so if we go into the products first you can see that if we try to add a product here you can see that we don't have any of the additional information about cupboards and books so there's probably absolutely no reason for us to utilize this as it is because we want to when we add details about the cupboard or book we also want to populate the products table right that's what we're trying to do so if we go into the books or cupboard you will see that we do have the uh the fields from the products and also then in this case the book the bottom here so let's just uh fill this in book one so we're just going to give this some information i'm sure you know how to do this i'm going to just skip this add some products and i'll see you in a second so once i've gone ahead i've added four items two in the books two in the cupboards now if we look at the default behavior for the products you can now see when we go back to the products table we actually have the four products are entered if we go into it you can see that we can access all the data except for the specific information that's related to the cupboards or stored in the cupboards and books table of course if we go to the couples or books table we can access all of the data so at this point nothing is working at this point so we just need to go into the what will be the uh the store and the views and we just need to make some changes in order to actually grab all the data from both so for each example i'm just going to try and perform a query where i can collect all the data from each model and display all the data onto the what is the home page here so if i go into my view i've just changed now this query so i'm going to run product dot objects to all so i'm going to look for the products table that's the parent table obviously and then i'm just going to extract all the data and display onto my what is the storefront here or the index or the home page so based upon the default behavior in the admin the products table only showed us information about the products data based upon the fields that were inside the product table and it didn't show us any of the fields that are associated or inside of the book or the cupboards table so maybe that's what's going to occur here so let's take a look so when we look at the home page we can see that the products are all displaying all the products are being selected from the products table now i don't currently have a setup where i'm trying to actually display any individual information about the book or the cupboard from those tables so let's just go into our hate index page in the templates and index here and just above price let's just uh copy this and let's uh let's say product and we want to get the author for example that's the author found in the book table so let's just see if that will actually get displayed so nothing is returned there so if we do want to get data from the related tables we're going to just need to extend this and say product dot and traverse down to book and then the author so that's going to collect the author so let's just give that a go refresh you can now see we've got the author from book one and book two so that's how we're going to collect the individual information if you're using this type of pattern from the other tables or sorry should i say from the from the child tables so this is where it gets a little bit more interesting let's have a look at the toolbar here so you can see that when we go down to sql it's telling us that we're running eight queries on this page so let's just uh delve into this so let's have a look what's happening here so we're running this first query select all from django session blah blah blah so this is just session information because i'm logged in i've created a session a django session so that's absolutely fine that's not really our concern at this point and you can see that i've selected also user uh where the author equals one because potentially i need to use that too so that's just out of scope here and also the category i'm selecting the category that's um not something we're interested in at this point so we're just interested in what we're trying to do here so select all from store product query by also order by store product created so here i'm selecting everything from the store so store product store being the app name um and product being the table so that's my first query and first of all i'm selecting all the data from the product table right so that's query number one so once i've done that what you can now see is that i seem to be hitting iterating over this product table and for every product i'm displaying i'm running a separate query because you can tell here it says select from essentially the select from the book table where the product id equals four so what's happening is i'm collecting all the data from the product table now i'm using that information the id essentially is going to match up the id that's in the book and the covered table so i'm utilizing that id the product id and matching it against the id the one-to-one field that's inside the book and the cupboard table and to get every piece of information i need to get all those ids and query them individually and in order to return the data so hopefully you understand hopefully i wasn't going to get a bit excited hopefully i wasn't too quick then hopefully you understand what's happening now so i'm iterating i'm searching and i'm making a query uh for every single product that i'm trying to collect and display on the home page now that's okay when i've got four items but what happens when i've got 100 items and i'm for example producing some sort of pagination and i want to collect all the items now that's when it gets a little bit uh costly to run this query potentially and then for example i might want to for example have a hundred people or a thousand people accessing this page so that's a lot of queries that are running just to produce a all the data from the tables so this is kind of like the fun bit working out now how can i reduce this load so i can produce more efficient sql and then potentially reduce the amount of sql queries i'm running maybe try and get this to maximum maybe two queries um maybe that's the case maybe can i cut this down to maybe two queries or maybe one query so is there a better approach so let's first add some covered data let's just do the amount of shelves i do apologize use all for that i didn't realize it doesn't matter but let's just put some cupboard data so shelves into the index here so um where we added the books information we want to also collect because at the moment we're not actually collecting any data from the from the cupboard so let's just uh get yeah let's just get the author shelf shelves okay so let's get the shelves from the cupboard so let's just run that query again see if anything changes okay so now we have 12 queries uh wow so because we've added that extra data we're essentially now doing a separate query to get that data uh in addition it looks like to also getting the general information so there's a lot going on here so you can see how that's expanding fairly quickly the amount of queries that we need to run so let's have a look at some of the tools that we've got to try and reduce the amount of queries here so the first one we have is is the select related okay so this works by creating an sql join uh and includes basically all the fields of the related object in the in this case in the select statement so essentially here we've got a select statement products also this is a select from select all from products and what we're doing now is we're using select related now we know what's related because we've made those related foreign keys those one-to-one keys or django has automatically to the sub classes the book and the cupboard table so select related then i've selected the two models and this is going to like i said create an sql join to include these fields when we create the sql statement which is going to produce less uh queries hopefully so let's go in and have a look to see if we can reduce these queries we refresh again and now we have four queries so it's worth introducing two things here first select related and then also the prefetch related so these do very similar tasks so let's just um change this to the pre-fetch related and let's have a look to see what happens so here we're running four queries now for refresh now we're running six so the pre-fetch in this instance like i said it's very situational this uh is running six queries now potentially here i'm just measuring based upon the queries now that isn't the whole picture but that's all i'm doing in this case so i'm saying you're generalizing here and saying the less queries is better now here's the thing and it's worth reading into but it looks as though the select related is essentially just running one query while prefix or the prefetch sorry is running two so we could say that the select related is probably faster however um over for example hundreds or thousands of models um potentially or depending on the scale of your database potentially the prefetch related could actually be better to use so it's worth experimenting and have a look and understanding more about the select related in prefix prefetch related because like i said at the start it can be very situational where you use them so to try and give you an understand the select related is using a join in the sql whereas the prefetch related is running a query on the first model it collects all the ids it needs to prefetch and then it runs a query with an in clause in where in the where sorry it runs it yeah it runs an ink clause in the where and all the ids that it needs so it's basically just how it works is slightly different um and like i said it's very situational i won't embellish any more apart from just to say have a little read into it because they are very useful tools so i do hope that was useful what i'm trying to give you is just some some small snippets i'm not trying to overburden you with lots of different information trying to be fairly specific and of course there's lots of tools that we could discuss looking at the bigger picture but it's good to know these small things to help us progress slowly into optimizing our application so let's move on to solution three which is abstract models so this is a slightly different approach now let's just go back to our model here so this was solution to multi-table inheritance now in this case we have a very similar set up here with the abstract method but in this case where is the multi-table inheritance made a table or dragon made a table for each of these classes what happens now when we use the abstract method all of these attributes or all of these fields in our table they would basically just get copied across to cupboard and book as well as their individual components or fields that have been described inside of their classes or inside of their tables so that's the key difference here between multi-table inheritance and then also the an abstract method so just to confirm these this product table isn't created what happens is we're inheriting these fields from this from this parent and this is all being copied or duplicated over to these new tables here the cupboard and the book so let's have a look at this so just going back into our code really there's just one change that we need to make here so what we need to do is we need to describe or define this product table as an abstract table so here we have uh abstract equals true so obviously we're going to need to change the code here in the other file so let's just go into the admin um let's just uh let's just blanket that out for a second we're not going to need that and of course we just need to go into the store migrations let's just delete this migration this is really annoying me move to the bin and then we're going to delete our database of course so let's just remove that so i'm going to go ahead and migrate and make migrations migrate so i'm going to recreate these tables again and then i just need to go ahead and again and just create a new super user and add some data so i'll see you once i've done that so i've created a super user so let's just actually have a look at the database first so let's go into the database so you can see here we've got the we should have the book in the cupboard so we've got the book and the cupboard but notice this time we've created an abstract class and we don't have a product table so let's just go into the book table you can see that when we go into the book table like i said previously all of these fields will be copied into the store book and that's exactly what's happened there and that will be the same of course in the cupboard table so you might be asking well what is the point of that because all we've done really is saved ourself copying and pasting in these fields into these what are now i guess concrete classes so what i introduced in the first solution that's a simply that's simply what we've done here that's pretty much all we've done so before we start adding data actually let's just now get rid of this migration uh so that's the table we've just built so let's just get rid of that all right let's just go back now and let's just name this a little bit more appropriately so this is going to be our base and then this is uh the product the book sorry so this is just going to uh with the abstract class uh this is basically just going to copy over these um fields as we know into our new tables here the book and the cupboard so we've called it bass so let's go ahead and run with that so what's the point of this so what can we do with this well what we can do is we can introduce a new class here a new table whereby we can create almost a a manual connection between this table and both of these tables here so if you remember in the first example essentially we've created a structure whereby we go through the products table to get to the book and cupboards table data that's what i showed you in the second solution so we can manually create that in actual fact by creating a new table and utilizing a generic foreign key to manually or to select data from these two or more tables so let's just run through this very quickly the code i don't want to type it out let's just paste it so i've created a new class here called product and i'm just trying to generalize here so this is uh this is going to be the product class which is going to be connected to the book and cupboard so i'm going to be able to access this data from the book and the cupboard data through the product class here through the product table and what i'm doing here is i'm creating content type um so what i want to do is define the two or more tables that i'm going to use so this is going to be essentially a drop down i'm selecting and when i'm filling in when i'm creating this data here i'm basically selecting the book table or i don't know what says tree there or the what's it called the cupboard table okay so there's my models i'm selecting so this second item here is a positive integer field so this is something that we we're going to manually add so what's happening here if i can try to explain when we add a book item that book is going to have an id so what we want to do is we want to populate this product table with first of all book and then secondly we want to define the id of that table that represents or connects to that particular book so if we add a book that's going to be id number one so when we create a new product based upon that we're going to insert number one in there and then select book in the first field so what we're going to do now is generate or create a a generic foreign key and from that we're going to need the content type so the actual table we want to select and then also the object id so the id of the object that's inside of the book or the cupboard and that's how we're going to connect the product table in a very manual manual way to the book and the cupboard or more tables so hopefully that makes sense um essentially we're just building the product table we had before in the previous example but i guess in a manual way almost so we're going to need to bring in the tools for this so we're going to need to bring in content type and the generic current um generic foreign key now i know that i haven't given you an explanation here i've just tried to give you an example of what exactly is happening here and hopefully you kind of understand based upon what i've said at general terms what's happening so please go ahead and have a look at generic foreign keys have a read through and it's very fairly simple to understand and the content type too okay so now we've got that in place i think we can now go ahead and just migrate again and then add some data so once i've added a new super user um i just need to go back into my admin again and just uh revert back my table so i want the product book and cupboard table so that should be okay now so i should now be able to run my server there we go so i have made a cpu user so i'm just going to now go into the admin area again and then like i said before so i just need to click on these links and now take you to the admin area and now we can explore the defaults here so let's first of all had a look have a look at um the books so it looks like uh hide this when we add a book we've got all the fields that we need wonderful and that's going to be the same with cupboards and then the products table you can see we've got two selections the table and then the object now this is going to be a manual process to begin with but we could automate this with code of course so what we want to do here is we want to add a book and at the same time add the details here into the product so that's going to be the content type and the object id of that particular book so when we make new date when we make new data inside of the books when we make new rows that increments the id of course so let's just add a new book so i'm just going to close book one i'll take you through one then i'll add a few more so is active publisher and author so i'll save that and now what i can now do is go into the book or the products and i can add a product so i want the book and the object id which is number one and save okay so i can now do the same thing for the cupboards so i'm going to add two items so next item in the products is going to be books id2 and then i need to do build two cupboards products and then add those into products and that's going to be id one and two as well because i'm using a different table remember so the increment is slightly different because it's a separate table so i'm going to go ahead and add those items so i've added all those items into products cupboard one and two and books one and two so now we can go ahead and go to the front end and do the same thing again as we did in the second solution and have a look at the queries so head over to the views right so we had this before so let's just uh oh what we did uh let's just uh get rid of that so let's bring in our our query again so we're using products again so let's just try this out product.object.org so we'll save that let's go into the front end we can find that let's go into our store again and now we're going to refresh so at the moment it doesn't look like it's uh collecting information so that doesn't look like it's uh useful so we're going to need to make a few changes here so let's have a look at the code so here in our index page you can see we're trying to loop through the data that we're returning from the database and then outputting the individual components image and title and so on so what we're going to need to do here is a simple change we're going to have to say inside of the products that returned we need to kind of traverse and go into that data that item and then access that data so here we're just going to add the item after the product in each section so let's uh go ahead and do that so product dot item dot author and then item dot shelves okay so we've added that data product we can add this to okay right so let's go back in and refresh and you can now see we've returned the data well at least some of the data i think we've uh not included the price item price so let's have a look at that so there we go so we have all the data back as per normal now so that was a simple small change we need to make so let's have a look at the actual query so we're running eight queries here so it's a similar situation in that what we're doing is we're collecting all the data from the product table and then using those ids to loop through each of um those tables and looking for those individual items that have been collected from the products table so one might one might imagine we can now go ahead and optimize that so let's just give this a go again let's use the prefix prefetch related um so let's add that on to the end and just see if we can now collect the data now what's happening here is it says cannot find book on product object book is invalid parameter to prefix related okay so what's happening here is that we don't actually have a reference point um so let's go back go back to model if you remember the second example the foreign key was in the book and the cupboard here we're kind of doing reverse in the foreign key or the key is in the product table now what we probably need to add in the book and the cupboard is a related name so what we need to do here then if we go into our models we need to build a many-to-many uh field over to the product table this will be one approach uh you can see we've created a related name and a query name that's just some parameters we can add in so we need a related name so you can see here we've done the same thing in the book uh we've made a many-to-many uh field in the book table again connecting it to the product table now this is kind of a manual setup of a of the setup we've done in the previous example almost now uh so now then what you'll need to do is make migrations and migrate that so once you've migrated restart the server come back and refresh and you'll see now it's actually working we're collecting the data again so this is running the prefix go back in the prefetch related query and you can see this time in actual fact we're running 12 queries now so it doesn't look like in this case it's making too much of a too many changes or 10 queries it looks like we're running um so i wonder for example in this case if i now change this so now let's move across to select related now this performed better didn't it in the first example so uh what we're going to need to do here is change to content type so we're going to need to select related content type now remember content type in our model is defining our two models book and cupboard so essentially we're going to choose our two models or select our data from our models through the content type book and cupboard now how that is formatted if you remember the format here is going to be uh the name of the app so store underscore book underscore related so what we're going to need to do here in addition to the changes we made there in the view is just go back into our related names in our book and our cupboard and we're going to need to change it to store underscore cupboard unscore related to match the products table so make those two changes in the cupboard and the book once you've done that you'll then be able to go back into the front end and then refresh and there we go we've got our data back so you can see here that the we're still running eight queries um which isn't ideal um so let's have a look at a different way of doing this so of course in this case i'm kind of just leading you down to this path and this idea here maybe it's not the best choice to go through the products table at all maybe we can just make a union of the two tables remember the two tables we have the books and the cupboard they have all the fields already inside of those tables so maybe we don't go through products here maybe we just make our own union here we are um because i've mentioned union i thought i might as well show you how to do this so what we're doing here is we're going to take the two tables remember these tables have all the fields already inside of more data so we're going to get collect all the data from the cupboard that's one query and then one query for the book collect all that data and then we're going to build a union so we take the cupboard and then we kind of connect it with the data that was returned from the book and then we just basically return that as one uh group of data one table for example and then as for normal we just send that across to our template so now we should just be able to go back into our page now data probably needs to be sorted so what's the problem here order buy not allowed in sub queries okay so orders a buy is not allowed in sub queries so that means if we go into our models you can see we have ordering here so we're probably going to need to do that within the individual classes here so you need to set that up separately in those different classes so let's just go back to our front end okay so let's not worry about the queries at the moment because we don't have the data so we're going to need to revert back in our view so we don't need oh sorry in our index we don't need item anymore so let's just get rid of item i do hope you're um following this uh it's useful if it is useful just let me know in the comments if it's not if there's something i missed well there's a lot of things i missed so they tell me what i miss there is lots of things i've missed out here um there's so many different ways it's just great um so i've reverted back now to that and let's just go back in i don't think this is gonna work just yet oh it does okay so there we go so what we have now is four queries so it looks like we're being a little bit more effective here so let's just go into our queries um that's great so we're getting our session data now we've got the auth user because we're logged in we're selecting the store category and also then select from store covered union select all from store book there we go so now we have four queries it looks nice and cleaner potentially that's improved performance so i will know at this point we only have four items in our database once we start scaling this up these type of tools and these type of methods that we're utilizing they may not be as of in as effective of course as i've already shown you there are some tools that potentially work more effectively in larger scales of data work at a larger scale of data i think i was right so yeah just have a go think about hopefully that's given you some inspiration in terms of kind of helping you improve your application so far now there's one more to go so let's have a look at the fourth approach solution four is django polymorphic and i do apologize i made a mistake earlier in the first introduction slide where i named it polymorphism now if you know a little bit about polymorphism in django terms you know that we have been actually talking about that more or less so let's just move on to the django polymorphic package so this is this package is going to perform those operations that we've been doing on its own essentially so this is a a simple way of creating these structures that we've been creating in our models um so have a look at the introduction to this and have a read through what this provides but we're just going to install it and have a look at what it provides us by doing that you'll see what it's doing based upon the information that i've already given you so let's go ahead and pip install so yeah let's just go ahead and pivot install django polymorphic there we go okie dokie and now we're going to need to look like add it above the contrib content types um so let's go ahead and do that um so let's bring in our products that's going to be in the core and the settings um so let's place it there there might be a reason for that i haven't read into that um okay so now we've got that uh making your models okay let's just go ahead and just tidy up here let's uh close everything down right so uh first of all we're going to need to go into our store and migrations let's just delete our migrations for now okay and then also we're going to delete our database let's just do this manually quickly and then also in our models um let's just go ahead and delete the product for now we're not going to need that and now we can have a look at what we need to do right so we've got these uh we've got these models here looks like we're going to need to bring in polymorphic uh model in so let's uh do that okay so let's uh bring in that at the top here looks like it's unresolved but we'll just ignore that for now okay so we're going to have our um product um and then let's add all the items into that so here we're defining it as a polymorphic model okay and then looks like we then have our child classes here um so let's go ahead and just add that into our product now here if we make the product polymorphic uh model then the char children are also going to be classed as a polymorphic model so all we need to do here is just add product so let's just get rid of that okay so that was simple and let's have a look now at the documentation i believe we need to do something a little bit different in the admin area so just moving into the admin uh we're going to need to bring in a polymorphic admin and we've got our models as per normal so for the parent admin we're going to extend from there so so we're going to bring in the we're going to create a base model here or base class sorry for all the childs so modeled a child admin um and we're going to bring in the polymorphic child model admin we're going to explicitly define our parent and then we're going to go into the what's going to be the book which is going to be a model a child admin and then also the cupboard okay and then finally we then are going to use the polymorphic model admin here in the the product okay okay then so from the top you can see that i've imported the polymorphic admin imported the parent model admin and the child model admin i've then gone ahead and created this class called model add child admin and that's basically a class that's going to import or kind of yeah it's going it's class it's going to include the two child's book and cupboard so you can see here we've added that to the model child admin and then we've also defined the base model there so that's all in and then here inside of each of these classes for the uh for the child's cupboards and book you can see we've identified the base model and to show an index so that's visible in the admin site and then finally this needs to be in order so finally we've created the product um so we created the product class here for admin we've defined the base model and then also the class models so now that's all defined what you'll need to do just go back into your models make sure you remove the many to many fields and then go ahead and make migrations and migrate add a new super user and add some data now it's going to look very familiar so i've already gone ahead and done that so once you've done that go over to the admin area and then just go to products and add a product and notice we're given a selection here of book and cupboard which is very interesting and then you save that and then you create your product as per normal that's interesting i'm not actually going to do that i'm going to come out of that and then go back into products okay so it didn't save okay so let's go ahead and actually have a look to see what's in the table it's going to be interesting so we've got our new table open database um so we've got a product table looks like we've got a book table and a cover table so let's have a look in the product table see what's inside of here it looks like we've got all of our fields okay and we've got this id here and then if we go into our cupboard here you can see that we've got the individual field so that's kind of set up there in the table it looks like we're probably running a a many to many table um i'm sorry one to one table from the cupboard to the product that looks like that's looks like that looks like what's happening here so we can see what's happening here so now all we need to do of course is go back into our views um let's just get rid of this here and let's just go back to a a classic product.objects.org and let's have a look to see what returns so back into our site we're going to refresh and now we've got a problem here so let's have a look to see what the problem is name products is not defined okay maybe i've called my model product maybe that's the problem i have indeed so let's go back into here oh no uh i am doing product uh so there's a problem here um products okay okay okay okay so i just need to um product equals product object there we go so i just need to add that into there okay now let's just go back into there and refresh so it looks like i have my data which is all good so let's have a look at the performance here so i'm running nine queries so let's have a look here so um so it looks like we're running lots of queries here we've got the inner joins as you'd expect now this is great because i'm not saying that one thing is quicker than something girls because again if we scale this up you could probably see that maybe this polymorphism polymorphic um the polymorphic package sorry is maybe going to outperform um but here you can see that our previous examples potentially are running less sql queries so potentially potentially in this case only um that this package might not be as effective as just creating it ourselves so hopefully that was useful okay so i've just done a refresh and you can now see in actual fact i've reduced that it's been reduced to six queries which is interesting um so there may have been some other setups there i didn't really read into the queue so looks like we're now running six queries so if you remember we did get this down to four queries so again that statement still applies so potentially this will work in a larger scale potentially more effectively than the other approaches but now at least you know some different approaches that you can test and try against your data so i do hope that exercise was useful or provided you some insights into thinking about optimizing your queries and also gave you some insights into different approaches for that particular problem that we set out at the beginning thank you very much for listening if you've got to the end if you feel as though you want to support the channel further please think about becoming a member of the channel that's always good and hopefully i'll see you in the next tutorial
Info
Channel: Very Academy
Views: 4,352
Rating: undefined out of 5
Keywords: python, python django, django sql, django return data, django orm, orm, django, django tutorial, djangotutorial, django tut, django 3, django examples, learn django, django beginners, beginners django, django queries, django database, django 2021, django performance, django database performance, django database opimisation, django abstract models
Id: Y4ahqzSs7nI
Channel Id: undefined
Length: 52min 55sec (3175 seconds)
Published: Sun Feb 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.