Piotr
Piotr

Reputation: 77

Django model.parameters

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!

Upvotes: 1

Views: 1322

Answers (2)

Mahender Thakur
Mahender Thakur

Reputation: 510

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.

Upvotes: 2

Dalvtor
Dalvtor

Reputation: 3286

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.

Upvotes: 1

Related Questions