Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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'."
  23. % field_name,
  24. obj=self,
  25. id="sites.E001",
  26. )
  27. ]
  28. if not field.many_to_many and not isinstance(field, (models.ForeignKey)):
  29. return [
  30. checks.Error(
  31. "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key "
  32. "or a many-to-many field."
  33. % (self.model._meta.object_name, field_name),
  34. obj=self,
  35. id="sites.E002",
  36. )
  37. ]
  38. return []
  39. def _get_field_name(self):
  40. """Return self.__field_name or 'site' or 'sites'."""
  41. if not self.__field_name:
  42. try:
  43. self.model._meta.get_field("site")
  44. except FieldDoesNotExist:
  45. self.__field_name = "sites"
  46. else:
  47. self.__field_name = "site"
  48. return self.__field_name
  49. def get_queryset(self):
  50. return (
  51. super()
  52. .get_queryset()
  53. .filter(**{self._get_field_name() + "__id": settings.SITE_ID})
  54. )