You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

67 lines
2.1 KiB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.conf import settings
  4. from django.core import checks
  5. from django.core.exceptions import FieldDoesNotExist
  6. from django.db import models
  7. class CurrentSiteManager(models.Manager):
  8. "Use this to limit objects to those associated with the current site."
  9. use_in_migrations = True
  10. def __init__(self, field_name=None):
  11. super(CurrentSiteManager, self).__init__()
  12. self.__field_name = field_name
  13. def check(self, **kwargs):
  14. errors = super(CurrentSiteManager, self).check(**kwargs)
  15. errors.extend(self._check_field_name())
  16. return errors
  17. def _check_field_name(self):
  18. field_name = self._get_field_name()
  19. try:
  20. field = self.model._meta.get_field(field_name)
  21. except FieldDoesNotExist:
  22. return [
  23. checks.Error(
  24. "CurrentSiteManager could not find a field named '%s'." % field_name,
  25. hint=None,
  26. obj=self,
  27. id='sites.E001',
  28. )
  29. ]
  30. if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
  31. return [
  32. checks.Error(
  33. "CurrentSiteManager cannot use '%s.%s' as it is not a ForeignKey or ManyToManyField." % (
  34. self.model._meta.object_name, field_name
  35. ),
  36. hint=None,
  37. obj=self,
  38. id='sites.E002',
  39. )
  40. ]
  41. return []
  42. def _get_field_name(self):
  43. """ Return self.__field_name or 'site' or 'sites'. """
  44. if not self.__field_name:
  45. try:
  46. self.model._meta.get_field('site')
  47. except FieldDoesNotExist:
  48. self.__field_name = 'sites'
  49. else:
  50. self.__field_name = 'site'
  51. return self.__field_name
  52. def get_queryset(self):
  53. return super(CurrentSiteManager, self).get_queryset().filter(
  54. **{self._get_field_name() + '__id': settings.SITE_ID})