Merge branch 'get_or_create_optizations' of https://github.com/wpjunior/mongoengine into get_or_create_optimizations

This commit is contained in:
Ross Lawley 2011-11-01 02:21:37 -07:00
commit 26f0c06624

View File

@ -739,18 +739,20 @@ class QuerySet(object):
""" """
self.__call__(*q_objs, **query) self.__call__(*q_objs, **query)
try: try:
result1 = self[0] result1 = self.next()
except IndexError: except StopIteration:
raise self._document.DoesNotExist("%s matching query does not exist." raise self._document.DoesNotExist("%s matching query does not exist."
% self._document._class_name) % self._document._class_name)
try: try:
result2 = self[1] result2 = self.next()
except IndexError: except StopIteration:
return result1 return result1
self.rewind()
message = u'%d items returned, instead of 1' % self.count() message = u'%d items returned, instead of 1' % self.count()
raise self._document.MultipleObjectsReturned(message) raise self._document.MultipleObjectsReturned(message)
def get_or_create(self, write_options=None, *q_objs, **query): def get_or_create(self, write_options=None, auto_save=True, *q_objs, **query):
"""Retrieve unique object or create, if it doesn't exist. Returns a tuple of """Retrieve unique object or create, if it doesn't exist. Returns a tuple of
``(object, created)``, where ``object`` is the retrieved or created object ``(object, created)``, where ``object`` is the retrieved or created object
and ``created`` is a boolean specifying whether a new object was created. Raises and ``created`` is a boolean specifying whether a new object was created. Raises
@ -765,23 +767,25 @@ class QuerySet(object):
Passes any write_options onto :meth:`~mongoengine.Document.save` Passes any write_options onto :meth:`~mongoengine.Document.save`
.. versionadded:: 0.3 .. versionadded:: 0.3
:param auto_save: if the object is to be saved automatically if not found.
.. versionadded:: 0.6
""" """
defaults = query.get('defaults', {}) defaults = query.get('defaults', {})
if 'defaults' in query: if 'defaults' in query:
del query['defaults'] del query['defaults']
self.__call__(*q_objs, **query) try:
count = self.count() doc = self.get(*q_objs, **query)
if count == 0: return doc, False
except self._document.DoesNotExist:
query.update(defaults) query.update(defaults)
doc = self._document(**query) doc = self._document(**query)
if auto_save:
doc.save(write_options=write_options) doc.save(write_options=write_options)
return doc, True return doc, True
elif count == 1:
return self.first(), False
else:
message = u'%d items returned, instead of 1' % count
raise self._document.MultipleObjectsReturned(message)
def create(self, **kwargs): def create(self, **kwargs):
"""Create new object. Returns the saved object instance. """Create new object. Returns the saved object instance.