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.

managers.py 1.9KB

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