parts/django/tests/modeltests/custom_managers/models.py
changeset 307 c6bca38c1cbf
equal deleted inserted replaced
306:5ff1fc726848 307:c6bca38c1cbf
       
     1 """
       
     2 23. Giving models a custom manager
       
     3 
       
     4 You can use a custom ``Manager`` in a particular model by extending the base
       
     5 ``Manager`` class and instantiating your custom ``Manager`` in your model.
       
     6 
       
     7 There are two reasons you might want to customize a ``Manager``: to add extra
       
     8 ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
       
     9 returns.
       
    10 """
       
    11 
       
    12 from django.db import models
       
    13 
       
    14 # An example of a custom manager called "objects".
       
    15 
       
    16 class PersonManager(models.Manager):
       
    17     def get_fun_people(self):
       
    18         return self.filter(fun=True)
       
    19 
       
    20 class Person(models.Model):
       
    21     first_name = models.CharField(max_length=30)
       
    22     last_name = models.CharField(max_length=30)
       
    23     fun = models.BooleanField()
       
    24     objects = PersonManager()
       
    25 
       
    26     def __unicode__(self):
       
    27         return u"%s %s" % (self.first_name, self.last_name)
       
    28 
       
    29 # An example of a custom manager that sets get_query_set().
       
    30 
       
    31 class PublishedBookManager(models.Manager):
       
    32     def get_query_set(self):
       
    33         return super(PublishedBookManager, self).get_query_set().filter(is_published=True)
       
    34 
       
    35 class Book(models.Model):
       
    36     title = models.CharField(max_length=50)
       
    37     author = models.CharField(max_length=30)
       
    38     is_published = models.BooleanField()
       
    39     published_objects = PublishedBookManager()
       
    40     authors = models.ManyToManyField(Person, related_name='books')
       
    41 
       
    42     def __unicode__(self):
       
    43         return self.title
       
    44 
       
    45 # An example of providing multiple custom managers.
       
    46 
       
    47 class FastCarManager(models.Manager):
       
    48     def get_query_set(self):
       
    49         return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150)
       
    50 
       
    51 class Car(models.Model):
       
    52     name = models.CharField(max_length=10)
       
    53     mileage = models.IntegerField()
       
    54     top_speed = models.IntegerField(help_text="In miles per hour.")
       
    55     cars = models.Manager()
       
    56     fast_cars = FastCarManager()
       
    57 
       
    58     def __unicode__(self):
       
    59         return self.name