PageRenderTime 13ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/modeltests/custom_managers/models.py

https://code.google.com/p/mango-py/
Python | 59 lines | 33 code | 13 blank | 13 comment | 0 complexity | 7dea533fbcf0d098ddf5d8ab58baaef8 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. 23. Giving models a custom manager
  3. You can use a custom ``Manager`` in a particular model by extending the base
  4. ``Manager`` class and instantiating your custom ``Manager`` in your model.
  5. There are two reasons you might want to customize a ``Manager``: to add extra
  6. ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
  7. returns.
  8. """
  9. from django.db import models
  10. # An example of a custom manager called "objects".
  11. class PersonManager(models.Manager):
  12. def get_fun_people(self):
  13. return self.filter(fun=True)
  14. class Person(models.Model):
  15. first_name = models.CharField(max_length=30)
  16. last_name = models.CharField(max_length=30)
  17. fun = models.BooleanField()
  18. objects = PersonManager()
  19. def __unicode__(self):
  20. return u"%s %s" % (self.first_name, self.last_name)
  21. # An example of a custom manager that sets get_query_set().
  22. class PublishedBookManager(models.Manager):
  23. def get_query_set(self):
  24. return super(PublishedBookManager, self).get_query_set().filter(is_published=True)
  25. class Book(models.Model):
  26. title = models.CharField(max_length=50)
  27. author = models.CharField(max_length=30)
  28. is_published = models.BooleanField()
  29. published_objects = PublishedBookManager()
  30. authors = models.ManyToManyField(Person, related_name='books')
  31. def __unicode__(self):
  32. return self.title
  33. # An example of providing multiple custom managers.
  34. class FastCarManager(models.Manager):
  35. def get_query_set(self):
  36. return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150)
  37. class Car(models.Model):
  38. name = models.CharField(max_length=10)
  39. mileage = models.IntegerField()
  40. top_speed = models.IntegerField(help_text="In miles per hour.")
  41. cars = models.Manager()
  42. fast_cars = FastCarManager()
  43. def __unicode__(self):
  44. return self.name