From 225972e151b8bead6842c6be4205f9e2771b2c3a Mon Sep 17 00:00:00 2001 From: Stephan Jaekel Date: Fri, 14 May 2010 14:03:18 +0200 Subject: [PATCH] Added some handy shortcuts for django users. --- mongoengine/django/shortcuts.py | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 mongoengine/django/shortcuts.py diff --git a/mongoengine/django/shortcuts.py b/mongoengine/django/shortcuts.py new file mode 100644 index 00000000..29bc17a8 --- /dev/null +++ b/mongoengine/django/shortcuts.py @@ -0,0 +1,45 @@ +from django.http import Http404 +from mongoengine.queryset import QuerySet +from mongoengine.base import BaseDocument + +def _get_queryset(cls): + """Inspired by django.shortcuts.*""" + if isinstance(cls, QuerySet): + return cls + else: + return cls.objects + +def get_document_or_404(cls, *args, **kwargs): + """ + Uses get() to return an document, or raises a Http404 exception if the document + does not exist. + + cls may be a Document or QuerySet object. All other passed + arguments and keyword arguments are used in the get() query. + + Note: Like with get(), an MultipleObjectsReturned will be raised if more than one + object is found. + + Inspired by django.shortcuts.* + """ + queryset = _get_queryset(cls) + try: + return queryset.get(*args, **kwargs) + except queryset._document.DoesNotExist: + raise Http404('No %s matches the given query.' % queryset._document._class_name) + +def get_list_or_404(cls, *args, **kwargs): + """ + Uses filter() to return a list of documents, or raise a Http404 exception if + the list is empty. + + cls may be a Document or QuerySet object. All other passed + arguments and keyword arguments are used in the filter() query. + + Inspired by django.shortcuts.* + """ + queryset = _get_queryset(cls) + obj_list = list(queryset.filter(*args, **kwargs)) + if not obj_list: + raise Http404('No %s matches the given query.' % queryset._document._class_name) + return obj_list