| 1 |
Model Managers |
| 2 |
============== |
| 3 |
|
| 4 |
InheritanceManager |
| 5 |
------------------ |
| 6 |
|
| 7 |
This manager (`contributed by Jeff Elmore`_) should be attached to a base model |
| 8 |
class in a model-inheritance tree. It allows queries on that base model to |
| 9 |
return heterogeneous results of the actual proper subtypes, without any |
| 10 |
additional queries. |
| 11 |
|
| 12 |
For instance, if you have a ``Place`` model with subclasses ``Restaurant`` and |
| 13 |
``Bar``, you may want to query all Places: |
| 14 |
|
| 15 |
.. code-block:: python |
| 16 |
|
| 17 |
nearby_places = Place.objects.filter(location='here') |
| 18 |
|
| 19 |
But when you iterate over ``nearby_places``, you'll get only ``Place`` |
| 20 |
instances back, even for objects that are "really" ``Restaurant`` or ``Bar``. |
| 21 |
If you attach an ``InheritanceManager`` to ``Place``, you can just call the |
| 22 |
``select_subclasses()`` method on the ``InheritanceManager`` or any |
| 23 |
``QuerySet`` from it, and the resulting objects will be instances of |
| 24 |
``Restaurant`` or ``Bar``: |
| 25 |
|
| 26 |
.. code-block:: python |
| 27 |
|
| 28 |
from model_utils.managers import InheritanceManager |
| 29 |
|
| 30 |
class Place(models.Model): |
| 31 |
# ... |
| 32 |
objects = InheritanceManager() |
| 33 |
|
| 34 |
class Restaurant(Place): |
| 35 |
# ... |
| 36 |
|
| 37 |
class Bar(Place): |
| 38 |
# ... |
| 39 |
|
| 40 |
nearby_places = Place.objects.filter(location='here').select_subclasses() |
| 41 |
for place in nearby_places: |
| 42 |
# "place" will automatically be an instance of Place, Restaurant, or Bar |
| 43 |
|
| 44 |
The database query performed will have an extra join for each subclass; if you |
| 45 |
want to reduce the number of joins and you only need particular subclasses to |
| 46 |
be returned as their actual type, you can pass subclass names to |
| 47 |
``select_subclasses()``, much like the built-in ``select_related()`` method: |
| 48 |
|
| 49 |
.. code-block:: python |
| 50 |
|
| 51 |
nearby_places = Place.objects.select_subclasses("restaurant") |
| 52 |
# restaurants will be Restaurant instances, bars will still be Place instances |
| 53 |
|
| 54 |
nearby_places = Place.objects.select_subclasses("restaurant", "bar") |
| 55 |
# all Places will be converted to Restaurant and Bar instances. |
| 56 |
|
| 57 |
It is also possible to use the subclasses themselves as arguments to |
| 58 |
``select_subclasses``, leaving it to calculate the relationship for you: |
| 59 |
|
| 60 |
.. code-block:: python |
| 61 |
|
| 62 |
nearby_places = Place.objects.select_subclasses(Restaurant) |
| 63 |
# restaurants will be Restaurant instances, bars will still be Place instances |
| 64 |
|
| 65 |
nearby_places = Place.objects.select_subclasses(Restaurant, Bar) |
| 66 |
# all Places will be converted to Restaurant and Bar instances. |
| 67 |
|
| 68 |
It is even possible to mix and match the two: |
| 69 |
|
| 70 |
.. code-block:: python |
| 71 |
|
| 72 |
nearby_places = Place.objects.select_subclasses(Restaurant, "bar") |
| 73 |
# all Places will be converted to Restaurant and Bar instances. |
| 74 |
|
| 75 |
``InheritanceManager`` also provides a subclass-fetching alternative to the |
| 76 |
``get()`` method: |
| 77 |
|
| 78 |
.. code-block:: python |
| 79 |
|
| 80 |
place = Place.objects.get_subclass(id=some_id) |
| 81 |
# "place" will automatically be an instance of Place, Restaurant, or Bar |
| 82 |
|
| 83 |
If you don't explicitly call ``select_subclasses()`` or ``get_subclass()``, |
| 84 |
an ``InheritanceManager`` behaves identically to a normal ``Manager``; so |
| 85 |
it's safe to use as your default manager for the model. |
| 86 |
|
| 87 |
.. _contributed by Jeff Elmore: https://jeffelmore.org/2010/11/11/automatic-downcasting-of-inherited-models-in-django/ |
| 88 |
|
| 89 |
JoinQueryset |
| 90 |
------------ |
| 91 |
|
| 92 |
A ``JoinQueryset`` will create a temporary table containing its own query result |
| 93 |
and join that temporary table with the model it is querying. This can |
| 94 |
be advantageous if you have to page through your entire DB and using django's |
| 95 |
slice mechanism to do that. ``LIMIT .. OFFSET ..`` becomes slower the bigger |
| 96 |
offset you use. |
| 97 |
|
| 98 |
.. code-block:: python |
| 99 |
|
| 100 |
sliced_qs = Place.objects.all()[2000:2010] |
| 101 |
qs = sliced_qs.join() |
| 102 |
# qs contains 10 objects, and there will be a much smaller performance hit |
| 103 |
# for paging through all of first 2000 objects. |
| 104 |
|
| 105 |
Alternatively, you can give it another queryset and ``JoinQueryset`` will create |
| 106 |
a temporary table containing the result of the given queryset and |
| 107 |
join that temporary table to itself. This can work as a more performant |
| 108 |
alternative to using django's ``__in`` as described in the following |
| 109 |
(`StackExchange answer`_). |
| 110 |
|
| 111 |
.. code-block:: python |
| 112 |
|
| 113 |
big_qs = Restaurant.objects.filter(menu='vegetarian') |
| 114 |
qs = Country.objects.filter(country_code='SE').join(big_qs) |
| 115 |
|
| 116 |
.. _StackExchange answer: https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in |
| 117 |
|
| 118 |
You can create a manager that produces ``JoinQueryset`` instances using ``JoinQueryset.as_manager()``. |
| 119 |
|
| 120 |
.. _QueryManager: |
| 121 |
|
| 122 |
QueryManager |
| 123 |
------------ |
| 124 |
|
| 125 |
Many custom model managers do nothing more than return a QuerySet that |
| 126 |
is filtered in some way. ``QueryManager`` allows you to express this |
| 127 |
pattern with a minimum of boilerplate: |
| 128 |
|
| 129 |
.. code-block:: python |
| 130 |
|
| 131 |
from django.db import models |
| 132 |
from model_utils.managers import QueryManager |
| 133 |
|
| 134 |
class Post(models.Model): |
| 135 |
... |
| 136 |
published = models.BooleanField() |
| 137 |
pub_date = models.DateField() |
| 138 |
... |
| 139 |
|
| 140 |
objects = models.Manager() |
| 141 |
public = QueryManager(published=True).order_by('-pub_date') |
| 142 |
|
| 143 |
The kwargs passed to ``QueryManager`` will be passed as-is to the |
| 144 |
``QuerySet.filter()`` method. You can also pass a ``Q`` object to |
| 145 |
``QueryManager`` to express more complex conditions. Note that you can |
| 146 |
set the ordering of the ``QuerySet`` returned by the ``QueryManager`` |
| 147 |
by chaining a call to ``.order_by()`` on the ``QueryManager`` (this is |
| 148 |
not required). |
| 149 |
|
| 150 |
SoftDeletableManager |
| 151 |
-------------------- |
| 152 |
|
| 153 |
Returns only model instances that have the ``is_removed`` field set |
| 154 |
to False. Uses ``SoftDeletableQuerySet``, which ensures model instances |
| 155 |
won't be removed in bulk, but they will be marked as removed instead. |
| 156 |
|
| 157 |
Mixins |
| 158 |
------ |
| 159 |
|
| 160 |
Each of the above manager classes has a corresponding mixin that can be used to |
| 161 |
add functionality to any manager. |
| 162 |
|
| 163 |
Note that any manager class using ``InheritanceManagerMixin`` must return a |
| 164 |
``QuerySet`` class using ``InheritanceQuerySetMixin`` from its ``get_queryset`` |
| 165 |
method. |