I'm going through a tough time trying to understand a part of the code I was given to review:
model.parameters.first()
It's a Django model,and though I know what the outcome is, I can't seem to find any word on "parameters" part.
I would be so grateful if you could either explain what does the "parameter" function do, or drop a link with the explanation. I couldn't find it anywhere in django documentation.
Thanks!
It looks like it is a custom manager .
Model.objects is the default manager provided by django, but we are allowed to create our own, so, if for instance, I had the model Post with the attribute published, I can create the PublishedManager.
class PublishedManager(models.Manager):
def unpublished(self):
return self.filter(published=False)
class Post(models.Model):
title = models.CharField(max_length=30)
published = models.BooleanField(default=True)
objects = PublishedManager()
I could easily do:
Post.objects.unpublished
Even though unpublished
is not an attribute of Post
.
This is a silly example but I hope you get the idea.
Django adds a Manager with the name "objects" to every Django model class. However, if you want to use a name other than "objects" for the Manager, you can rename it on a your-model as :
class YourModel(models.Model):
....
# custom manager replaces objects manager
parameters= models.Manager() # in your case
.....
So now i can do something like this :
YourModel.parameters.first()
Now YourModel.objects will generate an AttributeError .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.