shortcuts.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from mongoengine.queryset import QuerySet
  2. from mongoengine.base import BaseDocument
  3. from mongoengine.errors import ValidationError
  4. def _get_queryset(cls):
  5. """Inspired by django.shortcuts.*"""
  6. if isinstance(cls, QuerySet):
  7. return cls
  8. else:
  9. return cls.objects
  10. def get_document_or_404(cls, *args, **kwargs):
  11. """
  12. Uses get() to return an document, or raises a Http404 exception if the document
  13. does not exist.
  14. cls may be a Document or QuerySet object. All other passed
  15. arguments and keyword arguments are used in the get() query.
  16. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
  17. object is found.
  18. Inspired by django.shortcuts.*
  19. """
  20. queryset = _get_queryset(cls)
  21. try:
  22. return queryset.get(*args, **kwargs)
  23. except (queryset._document.DoesNotExist, ValidationError):
  24. from django.http import Http404
  25. raise Http404('No %s matches the given query.' % queryset._document._class_name)
  26. def get_list_or_404(cls, *args, **kwargs):
  27. """
  28. Uses filter() to return a list of documents, or raise a Http404 exception if
  29. the list is empty.
  30. cls may be a Document or QuerySet object. All other passed
  31. arguments and keyword arguments are used in the filter() query.
  32. Inspired by django.shortcuts.*
  33. """
  34. queryset = _get_queryset(cls)
  35. obj_list = list(queryset.filter(*args, **kwargs))
  36. if not obj_list:
  37. from django.http import Http404
  38. raise Http404('No %s matches the given query.' % queryset._document._class_name)
  39. return obj_list