2006-05-22 12:59:22 +08:00
|
|
|
from django.conf import settings
|
2006-05-22 13:17:25 +08:00
|
|
|
from django.db import models
|
|
|
|
from django.db.models.fields import FieldDoesNotExist
|
2006-05-22 12:59:22 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-05-22 12:59:22 +08:00
|
|
|
class CurrentSiteManager(models.Manager):
|
|
|
|
"Use this to limit objects to those associated with the current site."
|
2010-10-18 12:56:27 +08:00
|
|
|
def __init__(self, field_name=None):
|
2006-05-22 13:17:25 +08:00
|
|
|
super(CurrentSiteManager, self).__init__()
|
|
|
|
self.__field_name = field_name
|
2006-05-27 00:30:42 +08:00
|
|
|
self.__is_validated = False
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2010-10-18 12:56:27 +08:00
|
|
|
def _validate_field_name(self):
|
|
|
|
field_names = self.model._meta.get_all_field_names()
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2010-10-18 12:56:27 +08:00
|
|
|
# If a custom name is provided, make sure the field exists on the model
|
|
|
|
if self.__field_name is not None and self.__field_name not in field_names:
|
2013-10-18 08:24:41 +08:00
|
|
|
raise ValueError("%s couldn't find a field named %s in %s." %
|
2010-10-18 12:56:27 +08:00
|
|
|
(self.__class__.__name__, self.__field_name, self.model._meta.object_name))
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2010-10-18 12:56:27 +08:00
|
|
|
# Otherwise, see if there is a field called either 'site' or 'sites'
|
|
|
|
else:
|
|
|
|
for potential_name in ['site', 'sites']:
|
|
|
|
if potential_name in field_names:
|
|
|
|
self.__field_name = potential_name
|
|
|
|
self.__is_validated = True
|
|
|
|
break
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2010-10-18 12:56:27 +08:00
|
|
|
# Now do a type check on the field (FK or M2M only)
|
|
|
|
try:
|
|
|
|
field = self.model._meta.get_field(self.__field_name)
|
|
|
|
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
|
2013-10-23 18:09:29 +08:00
|
|
|
raise TypeError("%s must be a ForeignKey or ManyToManyField." % self.__field_name)
|
2010-10-18 12:56:27 +08:00
|
|
|
except FieldDoesNotExist:
|
2013-10-18 08:24:41 +08:00
|
|
|
raise ValueError("%s couldn't find a field named %s in %s." %
|
2010-10-18 12:56:27 +08:00
|
|
|
(self.__class__.__name__, self.__field_name, self.model._meta.object_name))
|
|
|
|
self.__is_validated = True
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2013-03-08 22:15:23 +08:00
|
|
|
def get_queryset(self):
|
2006-05-27 00:30:42 +08:00
|
|
|
if not self.__is_validated:
|
2010-10-18 12:56:27 +08:00
|
|
|
self._validate_field_name()
|
2013-03-08 22:15:23 +08:00
|
|
|
return super(CurrentSiteManager, self).get_queryset().filter(**{self.__field_name + '__id__exact': settings.SITE_ID})
|