/tests/modeltests/custom_managers/models.py
Python | 59 lines | 33 code | 13 blank | 13 comment | 0 complexity | 7dea533fbcf0d098ddf5d8ab58baaef8 MD5 | raw file
1""" 223. Giving models a custom manager 3 4You 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 7There 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`` 9returns. 10""" 11 12from django.db import models 13 14# An example of a custom manager called "objects". 15 16class PersonManager(models.Manager): 17 def get_fun_people(self): 18 return self.filter(fun=True) 19 20class 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 31class PublishedBookManager(models.Manager): 32 def get_query_set(self): 33 return super(PublishedBookManager, self).get_query_set().filter(is_published=True) 34 35class 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 47class FastCarManager(models.Manager): 48 def get_query_set(self): 49 return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150) 50 51class 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