Django Create Custom Manager Queryset

Here is how to create your own queryset on your model manager.
Below is my model definition.

class PhoneBook(models.Model):
    name = models.CharField(length=120)
    number = models.CharField(length=20)
    is_active = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name

And I used “.filter()” to fetch my data, for instance get all inactive phonebook.

PhoneBook.objects.filter(is_active=False)

But I need to create my own. So we can extend the default manager in our model. First of all create your own manager and define your queryset method within your manager.

class PhoneManager(models.Manager):
    def inactive(self):
        return self.filter(is_active=False)

Then modify your existing model to register your own manager.

class PhoneBook(models.Model):
    name = models.CharField(length=120)
    number = models.CharField(length=20)
    is_active = models.BooleanField(default=False)

    objects = PhoneManager()  # Your custom manager

    def __unicode__(self):
        return self.name

And now you can call your particular data by your own queryset.

PhoneBook.objects.inactive()

Reference: https://docs.djangoproject.com/en/dev/topics/db/managers/#managers

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s