| | 216 | The ``CurrentSiteManager`` |
|---|
| | 217 | ========================== |
|---|
| | 218 | |
|---|
| | 219 | If ``Site``s play a key role in your application, consider using the helpful |
|---|
| | 220 | ``CurrentSiteManager`` in your model(s). It's a model manager_ that |
|---|
| | 221 | automatically filters its queries to include only objects associated with the |
|---|
| | 222 | current ``Site``. |
|---|
| | 223 | |
|---|
| | 224 | Use ``CurrentSiteManager`` by adding it to your model explicitly. For example:: |
|---|
| | 225 | |
|---|
| | 226 | from django.db import models |
|---|
| | 227 | from django.contrib.sites.models import Site |
|---|
| | 228 | from django.contrib.sites.managers import CurrentSiteManager |
|---|
| | 229 | |
|---|
| | 230 | class Photo(models.Model): |
|---|
| | 231 | photo = models.FileField(upload_to='/home/photos') |
|---|
| | 232 | photographer_name = models.CharField(maxlength=100) |
|---|
| | 233 | pub_date = models.DateField() |
|---|
| | 234 | site = models.ForeignKey(Site) |
|---|
| | 235 | objects = models.Manager() |
|---|
| | 236 | on_site = CurrentSiteManager() |
|---|
| | 237 | |
|---|
| | 238 | With this model, ``Photo.objects.all()`` will return all ``Photo`` objects in |
|---|
| | 239 | the database, but ``Photo.on_site.all()`` will return only the ``Photo`` |
|---|
| | 240 | objects associated with the current site, according to the ``SITE_ID`` setting. |
|---|
| | 241 | |
|---|
| | 242 | How did ``CurrentSiteManager`` know which field of ``Photo`` was the ``Site``? |
|---|
| | 243 | It defaults to looking for a field called ``site``. If your model has a |
|---|
| | 244 | ``ForeignKey`` or ``ManyToManyField`` called something *other* than ``site``, |
|---|
| | 245 | you need to explicitly pass that as the parameter to ``CurrentSiteManager``. |
|---|
| | 246 | The following model, which has a field called ``publish_on``, demonstrates |
|---|
| | 247 | this:: |
|---|
| | 248 | |
|---|
| | 249 | from django.db import models |
|---|
| | 250 | from django.contrib.sites.models import Site |
|---|
| | 251 | from django.contrib.sites.managers import CurrentSiteManager |
|---|
| | 252 | |
|---|
| | 253 | class Photo(models.Model): |
|---|
| | 254 | photo = models.FileField(upload_to='/home/photos') |
|---|
| | 255 | photographer_name = models.CharField(maxlength=100) |
|---|
| | 256 | pub_date = models.DateField() |
|---|
| | 257 | publish_on = models.ForeignKey(Site) |
|---|
| | 258 | objects = models.Manager() |
|---|
| | 259 | on_site = CurrentSiteManager('publish_on') |
|---|
| | 260 | |
|---|
| | 261 | If you attempt to use ``CurrentSiteManager`` and pass a field name that doesn't |
|---|
| | 262 | exist, Django will raise a ``ValueError``. |
|---|
| | 263 | |
|---|
| | 264 | .. _manager: http://www.djangoproject.com/documentation/model_api/#managers |
|---|
| | 265 | |
|---|