manager.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from functools import partial
  2. from mongoengine.queryset.queryset import QuerySet
  3. __all__ = ('queryset_manager', 'QuerySetManager')
  4. class QuerySetManager(object):
  5. """
  6. The default QuerySet Manager.
  7. Custom QuerySet Manager functions can extend this class and users can
  8. add extra queryset functionality. Any custom manager methods must accept a
  9. :class:`~mongoengine.Document` class as its first argument, and a
  10. :class:`~mongoengine.queryset.QuerySet` as its second argument.
  11. The method function should return a :class:`~mongoengine.queryset.QuerySet`
  12. , probably the same one that was passed in, but modified in some way.
  13. """
  14. get_queryset = None
  15. default = QuerySet
  16. def __init__(self, queryset_func=None):
  17. if queryset_func:
  18. self.get_queryset = queryset_func
  19. def __get__(self, instance, owner):
  20. """Descriptor for instantiating a new QuerySet object when
  21. Document.objects is accessed.
  22. """
  23. if instance is not None:
  24. # Document object being used rather than a document class
  25. return self
  26. # owner is the document that contains the QuerySetManager
  27. queryset_class = owner._meta.get('queryset_class', self.default)
  28. queryset = queryset_class(owner, owner._get_collection())
  29. if self.get_queryset:
  30. arg_count = self.get_queryset.__code__.co_argcount
  31. if arg_count == 1:
  32. queryset = self.get_queryset(queryset)
  33. elif arg_count == 2:
  34. queryset = self.get_queryset(owner, queryset)
  35. else:
  36. queryset = partial(self.get_queryset, owner, queryset)
  37. return queryset
  38. def queryset_manager(func):
  39. """Decorator that allows you to define custom QuerySet managers on
  40. :class:`~mongoengine.Document` classes. The manager must be a function that
  41. accepts a :class:`~mongoengine.Document` class as its first argument, and a
  42. :class:`~mongoengine.queryset.QuerySet` as its second argument. The method
  43. function should return a :class:`~mongoengine.queryset.QuerySet`, probably
  44. the same one that was passed in, but modified in some way.
  45. """
  46. return QuerySetManager(func)