How to add custom django manager

In this article I'll show you how to create custom django manager. A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.

 

class Users(models.Model):

    
    password = models.CharField(max_length=256)
    email = models.CharField(max_length=255,unique= True)
    active=models.BooleanField(default=False)
    banuser=models.BooleanField(default=False)

       

    def __unicode__(self):
        return self.email

class ProductManager(models.Manager):
    def products_count(self,keyword):
        return self.filter(users__email=keyword).count()

STATUS_CHOICHES=(
    ('ava','Available'),
    ('not','Not Available'),
    )

class Products(models.Model):
    name=models.CharField(max_length=100)
    status=models.CharField(max_length=3,choices=STATUS_CHOICHES)
    users = models.ForeignKey(Users)
    objects=ProductManager()
    


    class Meta:
        verbose_name_plural="MY PRODUCTS"

 

In this example we added extra method products_count that count number of products for specific user

Products.objects.products_count("blaz1988@gmail.com")

 

email@djangotutsme.com Jan. 5, 2015, 8:42 a.m.