Learn the basics of Django's Model Managers and Querysets

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to a new tutorial in this one we're going to go through how to improve your django models by using custom model managers now managers are basically an interface that interacts with your database and you've actually been using a manager in the default man of the entire time so for example if you had like a post model every time you've been calling post objects dot all you've actually been using the default manager which is available through the model objects property and so we're going to take a look at how we can customize this using Django's model manager and so the project we're working out of has already been created if you go to github you can go all the way down to our django website and you can just clone or download this repository to follow along as we'll be working with the code inside here and this is just so that we already have some ready-made models to work with so once you've got everything installed and up and running then let's get started [Music] so inside our project we have a posts app and if we take a look at the models we have a post model which has a title description author which is a foreign key on the author model and that has a user email and a cell phone number and on our post model we have a few methods here to get the absolute URL which takes us to the detail view we then have one that takes us to the update view and one that takes us to the delete view and so what we're going to do is create ourselves a custom model manager and so by default this has already been available through the objects field on a model stub model that we're inheriting from and if you'd like to override that all you simply need to do is just create another class and so we'll just call this the post manager and we're going to say that it inherits from model stub manager and let's just say pause for now and what we do is we just say that our objects is equal to our post manager and we instantiate it like that and this basically means that we can go on to our post manager and we can define different methods to perform queries on the database and so for example we could create let's say an extra field here on the post and say this is the comments and it's basically like a comment count so we'll just say this is models dot integer field and we'll set the default equal to zero and here on our model manager we could say define smaller than and we pass himself and let's say we pass in size and we want to return all the posts that have a number of comments that is less than a certain value so we would just say return self where self refers to the model we're referring to so grab all the models where we will filter them where the comments is less than the size so this double underscore LT stands for less than and we set it equal to size and so let's actually make a migration here and then we'll say migrate and if we run the server again then we can head over here into our localhost and I'm going to go to the admin and we actually need to create a super user for that so we'll say Python manage SAP I create super user I'll just pass an admin and if we come in here and log in we've got the posts here so we'll just create a post the comments I'll say is let's say three and then I'll just say save and maybe we'll add another one and this one will say the comments are just one and then if we save that what we can do is open up the Python shell and we can test out our smaller than query here so what we'll do is we'll save from posts top models import post and then we'll just say post objects dot smaller than and then we just have to pass in the numbers let's say smaller than two and then we get a query set that has this another test which is the one that has only a comment of one and we could do the same kind of thing we could say define greater then and then we would say filter the comments that are greater than the size and so we can just exit out of this run it again and say from posts of models import post and then we'll call post objects dot greater than and let's say we want to pass where they are greater than two and then we get the test post which if we look at that one has three comments so the bottom line is that we can override the default model manager by specifying a class that inherits from Django's model manager and then here we can specify our own methods where we can filter the database according some kind of query and there's actually another way that we can do this we can comment this out and we'll create another class here and we'll say this is the post query set and this is basically going to inherit from models dot query set which is also something that comes from Django's models and here we're going to define the exact same methods as we did before except now we're going to reference the post query set as our object manager but we can actually access a property on the switches dot as manager so basically we allow the query set our own custom query set to perform as a manager as it would have done in this first way so let's just exit out of the terminal and we'll run this again and we'll call the exact same come on here and say post our objects not greater than two and we get the same result and so this is basically the introduction to how you can set up your own query set or your own manager on which you will specify all the methods that you would want as kind of like convenience methods because sometimes what we land up doing is defining methods like this on the class itself and this can end up completely cluttering the model itself whereas we could just handle all of those methods on a manager instead and so what we're going to do now is we're actually going to create a query set and a manager and let them work together so what I'm going to do is I'm going to create a new file here inside the posts app which will be called managers top high and it's going to take the same import from Django DB which is going to be models and basically what we want to do is just grab the post model manager and the query set and then we'll come and bring them here into the managers top I and then here we will import only the post manager so we'll say from top managers import the post manager and then here we can reference that as the manager for our post model and then we can just go back to the manager and what I'm going to do is bring the query set above the manager because we're going to reference it on the manager and so basically the logic here is that most of the methods from the standard query set are accessible directly from the manager and so basically the logic that's going to proceed here is that we're going to use the manager to call methods very conveniently with short syntax that will in turn call those methods on the query set that will perform the actual filtering or selecting of the data and so the way that we set this up is by defining a special method on the manager which is the get query set method so we just said get query set and it's going to take itself and what we're going to do is say return the post query set and we instantiate it and just pass in self dubbed model so that it knows what the model is for the query set and then we say using equals to self underscore DB and you can also find this in the documentation and basically what it's doing is it's just saying use the current database of this model to search for instances of this model and the model that were actually using is the model that's being referenced in the manager which in this case is the post so now we've done is we've linked our query set to the model manager and we can then create our methods on here to reference the query set on here so let's work through some examples so what I'll do is come down here and I'll say define maths posts and this is going to take himself and then we will say return self get query set and then say dot here we would then create the method on the query set that will actually handle this logic so what we'll do is we'll say define get maths posts which we'll take in self and all we're going to do is filter all the post objects where the author is equal to the Matt user so we'll just say return self so the post models and we'll say filter where the author double underscore username equals two and then we'll say this is Matt or admin for example in that case what we could even do is pass in the username dynamically so we could say get users posts that takes itself and a username and then we'll just say this is the method on the query set to actually pass in over here and we'll pass in the username here and say define users posts and we can even call this get users posts and then pass in the username into this function of get users posts on the query set and I'm gonna delete these two as well and get rid of them there as well so now we have the query set it's going to handle actually filtering the models according to this condition where the author's username is the username being passed in and our manager is just referencing it off of the query set and this can be convenient because then all the logic is actually held on the query set in terms of filtering the data whereas our manager holds all of the unique methods that we would consider convenient for the model so let's head over to the views and here we have a post list so what we'll do is we'll say admins posts equals to posts objects dot and then we go back to the managers and we say dot get users posts and we'll pass in the username would say this is admin and we'll pass this in here as well admins posts is admins posts and now we can just go to the templates here so to post list and what we'll do is actually just copy it that one there paste it here and we'll add an HR tag there as well and say for post in admins posts create a row and I'll add an h2 tag here that says admins posts and there we go now let's come in here and we'll go to slash posts and we're getting an invalid lookup which basically means that username is not a field on this model so if we check we've got the user first that we need to check so this is basically got to be double underscore user and then double underscore username so basically going from the author to its corresponding user and then grabbing the user name field off of the user and now we see it works so we've got all the posts here test post and another test and then we've got the admins posts here so let's go into the admin and for the test post we will create a new user or new author author and we'll create a new user for that author where the user name can be Matt and then we'll just add a dummy email there and now we've changed the author to be Matt and we'll just say save come back in here refresh this and so now we've got this one which is written by Matt and this one which is written by admin and then you've got admins posts which is only this one written by admin and so that's a very basic kind of filtering that's taking place but we can pretty much do anything our heart desires and so say we actually had another model here let's create another one and we'll call this the editor then this editor has a user and we don't need an email or cell phone number so we'll just keep that and then we can come to the post and let's say we have an editor which is models dot foreign key on the editor model and will say on the leads equals two models dot cascade and I'm actually just going to set blank and null to be true so that we don't get any errors in the database and we'll say manage the pipe make migrations there we go now we can say migrate and then we can run the server again and basically what we can do now is we can create one which would be called an author manager and we'll come back to the managers here and call this on the author manager and we'll copy the exact same thing here and let's call this one the editor manager and they can both reference the post query set like that and we could call this on me get author posts and we could copy this exact same thing there and say define get editors or get editor posts and instead of filtering the author we would fall to the editor and we can keep this method the same get users posts and get users posts and reference both of these model managers on our post model so this one we could call the author and this one we could call the editor and said this is the editor manager and then just import this at the top here just like that and actually instead of calling it author and editor because we've named those fields they will call this the authors and editors like that and so now when we come into the admin if we come back here we can specify the author and the editor so let's come back and actually we can pass this into the admin as well so we'll import editor and register the editor and if we come back here let's add an editor and we'll create a new user and we'll call this guy editor dude and when you save that there's our one editor and so now we can just assign that editor user to this user here and we'll save that go back to the posts and we can assign him as the editor to that post and then we can come back to our views and let's say that this is editor dudes posts and we'll say post dot editors dot get users posts for editor dude and then this one would be posted authors that get users posts of admin and then we can pass additives posts in like this and there we go and now let's go to the post list here and again I'll just copy all of that there post that there and this will be editor dudes posts where this is editor dudes posts that will loop through and if we save that and come back here and refresh the page and now we're just getting a has no attribute objects and that's just coming from this all posts here because we don't have an object's manager anymore so we could just reference this off of the author's one and then we can just go back to the manager here and say define all which takes in self and we'll just say return self get query set and then here we just need to fix these methods here so get users posts on the author manager can reference the get authors posts and then the get editor posts can be referenced here on the gate user posts for the editor manager and so now if we come back here and refresh this now we've got first all of the posts showing it's a test post written by Matt and this one by admin then we've got admins posts which is written by admin and we've got edited dudes posts that are written by admin but this one does have a latitude as an editor it's just not showing here that's what we wanted to cover in this one introducing the concept of model managers and query sets we aren't doing really advanced filtering the purpose of this video is purely just to introduce you to this concept of the managers so you can outsource that logic from your models into the managers where you can actually eliminate a lot of this logic even these methods with returning a URL such as these absolute URLs update and delete URLs so if you enjoyed this video leave a comment down below and let us know what you thought and otherwise thanks for watching don't forget to subscribe and we'll see you in the next one [Music]
Info
Channel: JustDjango
Views: 32,939
Rating: undefined out of 5
Keywords: django, django tutorial, python django, python, Django Web Framework (Software), Python, python 3, django python, python tutorial, how to python django, django 2.0 tutorial, django models, django managers, django queryests, django model managers
Id: rjUmA_pkGtw
Channel Id: undefined
Length: 19min 37sec (1177 seconds)
Published: Mon Dec 31 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.