document.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. import re
  2. import warnings
  3. from bson.dbref import DBRef
  4. import pymongo
  5. from pymongo.read_preferences import ReadPreference
  6. import six
  7. from mongoengine import signals
  8. from mongoengine.base import (BaseDict, BaseDocument, BaseList,
  9. DocumentMetaclass, EmbeddedDocumentList,
  10. TopLevelDocumentMetaclass, get_document)
  11. from mongoengine.common import _import_class
  12. from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
  13. from mongoengine.context_managers import switch_collection, switch_db
  14. from mongoengine.errors import (InvalidDocumentError, InvalidQueryError,
  15. SaveConditionError)
  16. from mongoengine.python_support import IS_PYMONGO_3
  17. from mongoengine.queryset import (NotUniqueError, OperationError,
  18. QuerySet, transform)
  19. __all__ = ('Document', 'EmbeddedDocument', 'DynamicDocument',
  20. 'DynamicEmbeddedDocument', 'OperationError',
  21. 'InvalidCollectionError', 'NotUniqueError', 'MapReduceDocument')
  22. def includes_cls(fields):
  23. """Helper function used for ensuring and comparing indexes."""
  24. first_field = None
  25. if len(fields):
  26. if isinstance(fields[0], six.string_types):
  27. first_field = fields[0]
  28. elif isinstance(fields[0], (list, tuple)) and len(fields[0]):
  29. first_field = fields[0][0]
  30. return first_field == '_cls'
  31. class InvalidCollectionError(Exception):
  32. pass
  33. class EmbeddedDocument(six.with_metaclass(DocumentMetaclass, BaseDocument)):
  34. """A :class:`~mongoengine.Document` that isn't stored in its own
  35. collection. :class:`~mongoengine.EmbeddedDocument`\ s should be used as
  36. fields on :class:`~mongoengine.Document`\ s through the
  37. :class:`~mongoengine.EmbeddedDocumentField` field type.
  38. A :class:`~mongoengine.EmbeddedDocument` subclass may be itself subclassed,
  39. to create a specialised version of the embedded document that will be
  40. stored in the same collection. To facilitate this behaviour a `_cls`
  41. field is added to documents (hidden though the MongoEngine interface).
  42. To enable this behaviour set :attr:`allow_inheritance` to ``True`` in the
  43. :attr:`meta` dictionary.
  44. """
  45. __slots__ = ('_instance', )
  46. # The __metaclass__ attribute is removed by 2to3 when running with Python3
  47. # my_metaclass is defined so that metaclass can be queried in Python 2 & 3
  48. my_metaclass = DocumentMetaclass
  49. # A generic embedded document doesn't have any immutable properties
  50. # that describe it uniquely, hence it shouldn't be hashable. You can
  51. # define your own __hash__ method on a subclass if you need your
  52. # embedded documents to be hashable.
  53. __hash__ = None
  54. def __init__(self, *args, **kwargs):
  55. super(EmbeddedDocument, self).__init__(*args, **kwargs)
  56. self._instance = None
  57. self._changed_fields = []
  58. def __eq__(self, other):
  59. if isinstance(other, self.__class__):
  60. return self._data == other._data
  61. return False
  62. def __ne__(self, other):
  63. return not self.__eq__(other)
  64. def to_mongo(self, *args, **kwargs):
  65. data = super(EmbeddedDocument, self).to_mongo(*args, **kwargs)
  66. # remove _id from the SON if it's in it and it's None
  67. if '_id' in data and data['_id'] is None:
  68. del data['_id']
  69. return data
  70. def save(self, *args, **kwargs):
  71. self._instance.save(*args, **kwargs)
  72. def reload(self, *args, **kwargs):
  73. self._instance.reload(*args, **kwargs)
  74. class Document(six.with_metaclass(TopLevelDocumentMetaclass, BaseDocument)):
  75. """The base class used for defining the structure and properties of
  76. collections of documents stored in MongoDB. Inherit from this class, and
  77. add fields as class attributes to define a document's structure.
  78. Individual documents may then be created by making instances of the
  79. :class:`~mongoengine.Document` subclass.
  80. By default, the MongoDB collection used to store documents created using a
  81. :class:`~mongoengine.Document` subclass will be the name of the subclass
  82. converted to lowercase. A different collection may be specified by
  83. providing :attr:`collection` to the :attr:`meta` dictionary in the class
  84. definition.
  85. A :class:`~mongoengine.Document` subclass may be itself subclassed, to
  86. create a specialised version of the document that will be stored in the
  87. same collection. To facilitate this behaviour a `_cls`
  88. field is added to documents (hidden though the MongoEngine interface).
  89. To enable this behaviourset :attr:`allow_inheritance` to ``True`` in the
  90. :attr:`meta` dictionary.
  91. A :class:`~mongoengine.Document` may use a **Capped Collection** by
  92. specifying :attr:`max_documents` and :attr:`max_size` in the :attr:`meta`
  93. dictionary. :attr:`max_documents` is the maximum number of documents that
  94. is allowed to be stored in the collection, and :attr:`max_size` is the
  95. maximum size of the collection in bytes. :attr:`max_size` is rounded up
  96. to the next multiple of 256 by MongoDB internally and mongoengine before.
  97. Use also a multiple of 256 to avoid confusions. If :attr:`max_size` is not
  98. specified and :attr:`max_documents` is, :attr:`max_size` defaults to
  99. 10485760 bytes (10MB).
  100. Indexes may be created by specifying :attr:`indexes` in the :attr:`meta`
  101. dictionary. The value should be a list of field names or tuples of field
  102. names. Index direction may be specified by prefixing the field names with
  103. a **+** or **-** sign.
  104. Automatic index creation can be disabled by specifying
  105. :attr:`auto_create_index` in the :attr:`meta` dictionary. If this is set to
  106. False then indexes will not be created by MongoEngine. This is useful in
  107. production systems where index creation is performed as part of a
  108. deployment system.
  109. By default, _cls will be added to the start of every index (that
  110. doesn't contain a list) if allow_inheritance is True. This can be
  111. disabled by either setting cls to False on the specific index or
  112. by setting index_cls to False on the meta dictionary for the document.
  113. By default, any extra attribute existing in stored data but not declared
  114. in your model will raise a :class:`~mongoengine.FieldDoesNotExist` error.
  115. This can be disabled by setting :attr:`strict` to ``False``
  116. in the :attr:`meta` dictionary.
  117. """
  118. # The __metaclass__ attribute is removed by 2to3 when running with Python3
  119. # my_metaclass is defined so that metaclass can be queried in Python 2 & 3
  120. my_metaclass = TopLevelDocumentMetaclass
  121. __slots__ = ('__objects',)
  122. @property
  123. def pk(self):
  124. """Get the primary key."""
  125. if 'id_field' not in self._meta:
  126. return None
  127. return getattr(self, self._meta['id_field'])
  128. @pk.setter
  129. def pk(self, value):
  130. """Set the primary key."""
  131. return setattr(self, self._meta['id_field'], value)
  132. def __hash__(self):
  133. """Return the hash based on the PK of this document. If it's new
  134. and doesn't have a PK yet, return the default object hash instead.
  135. """
  136. if self.pk is None:
  137. return super(BaseDocument, self).__hash__()
  138. return hash(self.pk)
  139. @classmethod
  140. def _get_db(cls):
  141. """Some Model using other db_alias"""
  142. return get_db(cls._meta.get('db_alias', DEFAULT_CONNECTION_NAME))
  143. @classmethod
  144. def _get_collection(cls):
  145. """Return a PyMongo collection for the document."""
  146. if not hasattr(cls, '_collection') or cls._collection is None:
  147. # Get the collection, either capped or regular.
  148. if cls._meta.get('max_size') or cls._meta.get('max_documents'):
  149. cls._collection = cls._get_capped_collection()
  150. else:
  151. db = cls._get_db()
  152. collection_name = cls._get_collection_name()
  153. cls._collection = db[collection_name]
  154. # Ensure indexes on the collection unless auto_create_index was
  155. # set to False.
  156. # Also there is no need to ensure indexes on slave.
  157. db = cls._get_db()
  158. if cls._meta.get('auto_create_index', True) and\
  159. db.client.is_primary:
  160. cls.ensure_indexes()
  161. return cls._collection
  162. @classmethod
  163. def _get_capped_collection(cls):
  164. """Create a new or get an existing capped PyMongo collection."""
  165. db = cls._get_db()
  166. collection_name = cls._get_collection_name()
  167. # Get max document limit and max byte size from meta.
  168. max_size = cls._meta.get('max_size') or 10 * 2 ** 20 # 10MB default
  169. max_documents = cls._meta.get('max_documents')
  170. # MongoDB will automatically raise the size to make it a multiple of
  171. # 256 bytes. We raise it here ourselves to be able to reliably compare
  172. # the options below.
  173. if max_size % 256:
  174. max_size = (max_size // 256 + 1) * 256
  175. # If the collection already exists and has different options
  176. # (i.e. isn't capped or has different max/size), raise an error.
  177. if collection_name in db.collection_names():
  178. collection = db[collection_name]
  179. options = collection.options()
  180. if (
  181. options.get('max') != max_documents or
  182. options.get('size') != max_size
  183. ):
  184. raise InvalidCollectionError(
  185. 'Cannot create collection "{}" as a capped '
  186. 'collection as it already exists'.format(cls._collection)
  187. )
  188. return collection
  189. # Create a new capped collection.
  190. opts = {'capped': True, 'size': max_size}
  191. if max_documents:
  192. opts['max'] = max_documents
  193. return db.create_collection(collection_name, **opts)
  194. def to_mongo(self, *args, **kwargs):
  195. data = super(Document, self).to_mongo(*args, **kwargs)
  196. # If '_id' is None, try and set it from self._data. If that
  197. # doesn't exist either, remote '_id' from the SON completely.
  198. if data['_id'] is None:
  199. if self._data.get('id') is None:
  200. del data['_id']
  201. else:
  202. data['_id'] = self._data['id']
  203. return data
  204. def modify(self, query=None, **update):
  205. """Perform an atomic update of the document in the database and reload
  206. the document object using updated version.
  207. Returns True if the document has been updated or False if the document
  208. in the database doesn't match the query.
  209. .. note:: All unsaved changes that have been made to the document are
  210. rejected if the method returns True.
  211. :param query: the update will be performed only if the document in the
  212. database matches the query
  213. :param update: Django-style update keyword arguments
  214. """
  215. if query is None:
  216. query = {}
  217. if self.pk is None:
  218. raise InvalidDocumentError('The document does not have a primary key.')
  219. id_field = self._meta['id_field']
  220. query = query.copy() if isinstance(query, dict) else query.to_query(self)
  221. if id_field not in query:
  222. query[id_field] = self.pk
  223. elif query[id_field] != self.pk:
  224. raise InvalidQueryError('Invalid document modify query: it must modify only this document.')
  225. # Need to add shard key to query, or you get an error
  226. query.update(self._object_key)
  227. updated = self._qs(**query).modify(new=True, **update)
  228. if updated is None:
  229. return False
  230. for field in self._fields_ordered:
  231. setattr(self, field, self._reload(field, updated[field]))
  232. self._changed_fields = updated._changed_fields
  233. self._created = False
  234. return True
  235. def save(self, force_insert=False, validate=True, clean=True,
  236. write_concern=None, cascade=None, cascade_kwargs=None,
  237. _refs=None, save_condition=None, signal_kwargs=None, **kwargs):
  238. """Save the :class:`~mongoengine.Document` to the database. If the
  239. document already exists, it will be updated, otherwise it will be
  240. created.
  241. :param force_insert: only try to create a new document, don't allow
  242. updates of existing documents.
  243. :param validate: validates the document; set to ``False`` to skip.
  244. :param clean: call the document clean method, requires `validate` to be
  245. True.
  246. :param write_concern: Extra keyword arguments are passed down to
  247. :meth:`~pymongo.collection.Collection.save` OR
  248. :meth:`~pymongo.collection.Collection.insert`
  249. which will be used as options for the resultant
  250. ``getLastError`` command. For example,
  251. ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
  252. wait until at least two servers have recorded the write and
  253. will force an fsync on the primary server.
  254. :param cascade: Sets the flag for cascading saves. You can set a
  255. default by setting "cascade" in the document __meta__
  256. :param cascade_kwargs: (optional) kwargs dictionary to be passed throw
  257. to cascading saves. Implies ``cascade=True``.
  258. :param _refs: A list of processed references used in cascading saves
  259. :param save_condition: only perform save if matching record in db
  260. satisfies condition(s) (e.g. version number).
  261. Raises :class:`OperationError` if the conditions are not satisfied
  262. :param signal_kwargs: (optional) kwargs dictionary to be passed to
  263. the signal calls.
  264. .. versionchanged:: 0.5
  265. In existing documents it only saves changed fields using
  266. set / unset. Saves are cascaded and any
  267. :class:`~bson.dbref.DBRef` objects that have changes are
  268. saved as well.
  269. .. versionchanged:: 0.6
  270. Added cascading saves
  271. .. versionchanged:: 0.8
  272. Cascade saves are optional and default to False. If you want
  273. fine grain control then you can turn off using document
  274. meta['cascade'] = True. Also you can pass different kwargs to
  275. the cascade save using cascade_kwargs which overwrites the
  276. existing kwargs with custom values.
  277. .. versionchanged:: 0.8.5
  278. Optional save_condition that only overwrites existing documents
  279. if the condition is satisfied in the current db record.
  280. .. versionchanged:: 0.10
  281. :class:`OperationError` exception raised if save_condition fails.
  282. .. versionchanged:: 0.10.1
  283. :class: save_condition failure now raises a `SaveConditionError`
  284. .. versionchanged:: 0.10.7
  285. Add signal_kwargs argument
  286. """
  287. if self._meta.get('abstract'):
  288. raise InvalidDocumentError('Cannot save an abstract document.')
  289. signal_kwargs = signal_kwargs or {}
  290. signals.pre_save.send(self.__class__, document=self, **signal_kwargs)
  291. if validate:
  292. self.validate(clean=clean)
  293. if write_concern is None:
  294. write_concern = {'w': 1}
  295. doc = self.to_mongo()
  296. created = ('_id' not in doc or self._created or force_insert)
  297. signals.pre_save_post_validation.send(self.__class__, document=self,
  298. created=created, **signal_kwargs)
  299. # it might be refreshed by the pre_save_post_validation hook, e.g., for etag generation
  300. doc = self.to_mongo()
  301. if self._meta.get('auto_create_index', True):
  302. self.ensure_indexes()
  303. try:
  304. # Save a new document or update an existing one
  305. if created:
  306. object_id = self._save_create(doc, force_insert, write_concern)
  307. else:
  308. object_id, created = self._save_update(doc, save_condition,
  309. write_concern)
  310. if cascade is None:
  311. cascade = (self._meta.get('cascade', False) or
  312. cascade_kwargs is not None)
  313. if cascade:
  314. kwargs = {
  315. 'force_insert': force_insert,
  316. 'validate': validate,
  317. 'write_concern': write_concern,
  318. 'cascade': cascade
  319. }
  320. if cascade_kwargs: # Allow granular control over cascades
  321. kwargs.update(cascade_kwargs)
  322. kwargs['_refs'] = _refs
  323. self.cascade_save(**kwargs)
  324. except pymongo.errors.DuplicateKeyError as err:
  325. message = u'Tried to save duplicate unique keys (%s)'
  326. raise NotUniqueError(message % six.text_type(err))
  327. except pymongo.errors.OperationFailure as err:
  328. message = 'Could not save document (%s)'
  329. if re.match('^E1100[01] duplicate key', six.text_type(err)):
  330. # E11000 - duplicate key error index
  331. # E11001 - duplicate key on update
  332. message = u'Tried to save duplicate unique keys (%s)'
  333. raise NotUniqueError(message % six.text_type(err))
  334. raise OperationError(message % six.text_type(err))
  335. # Make sure we store the PK on this document now that it's saved
  336. id_field = self._meta['id_field']
  337. if created or id_field not in self._meta.get('shard_key', []):
  338. self[id_field] = self._fields[id_field].to_python(object_id)
  339. signals.post_save.send(self.__class__, document=self,
  340. created=created, **signal_kwargs)
  341. self._clear_changed_fields()
  342. self._created = False
  343. return self
  344. def _save_create(self, doc, force_insert, write_concern):
  345. """Save a new document.
  346. Helper method, should only be used inside save().
  347. """
  348. collection = self._get_collection()
  349. if force_insert:
  350. return collection.insert(doc, **write_concern)
  351. object_id = collection.save(doc, **write_concern)
  352. # In PyMongo 3.0, the save() call calls internally the _update() call
  353. # but they forget to return the _id value passed back, therefore getting it back here
  354. # Correct behaviour in 2.X and in 3.0.1+ versions
  355. if not object_id and pymongo.version_tuple == (3, 0):
  356. pk_as_mongo_obj = self._fields.get(self._meta['id_field']).to_mongo(self.pk)
  357. object_id = (
  358. self._qs.filter(pk=pk_as_mongo_obj).first() and
  359. self._qs.filter(pk=pk_as_mongo_obj).first().pk
  360. ) # TODO doesn't this make 2 queries?
  361. return object_id
  362. def _get_update_doc(self):
  363. """Return a dict containing all the $set and $unset operations
  364. that should be sent to MongoDB based on the changes made to this
  365. Document.
  366. """
  367. updates, removals = self._delta()
  368. update_doc = {}
  369. if updates:
  370. update_doc['$set'] = updates
  371. if removals:
  372. update_doc['$unset'] = removals
  373. return update_doc
  374. def _save_update(self, doc, save_condition, write_concern):
  375. """Update an existing document.
  376. Helper method, should only be used inside save().
  377. """
  378. collection = self._get_collection()
  379. object_id = doc['_id']
  380. created = False
  381. select_dict = {}
  382. if save_condition is not None:
  383. select_dict = transform.query(self.__class__, **save_condition)
  384. select_dict['_id'] = object_id
  385. # Need to add shard key to query, or you get an error
  386. shard_key = self._meta.get('shard_key', tuple())
  387. for k in shard_key:
  388. path = self._lookup_field(k.split('.'))
  389. actual_key = [p.db_field for p in path]
  390. val = doc
  391. for ak in actual_key:
  392. val = val[ak]
  393. select_dict['.'.join(actual_key)] = val
  394. update_doc = self._get_update_doc()
  395. if update_doc:
  396. upsert = save_condition is None
  397. last_error = collection.update(select_dict, update_doc,
  398. upsert=upsert, **write_concern)
  399. if not upsert and last_error['n'] == 0:
  400. raise SaveConditionError('Race condition preventing'
  401. ' document update detected')
  402. if last_error is not None:
  403. updated_existing = last_error.get('updatedExisting')
  404. if updated_existing is False:
  405. created = True
  406. # !!! This is bad, means we accidentally created a new,
  407. # potentially corrupted document. See
  408. # https://github.com/MongoEngine/mongoengine/issues/564
  409. return object_id, created
  410. def cascade_save(self, **kwargs):
  411. """Recursively save any references and generic references on the
  412. document.
  413. """
  414. _refs = kwargs.get('_refs') or []
  415. ReferenceField = _import_class('ReferenceField')
  416. GenericReferenceField = _import_class('GenericReferenceField')
  417. for name, cls in self._fields.items():
  418. if not isinstance(cls, (ReferenceField,
  419. GenericReferenceField)):
  420. continue
  421. ref = self._data.get(name)
  422. if not ref or isinstance(ref, DBRef):
  423. continue
  424. if not getattr(ref, '_changed_fields', True):
  425. continue
  426. ref_id = "%s,%s" % (ref.__class__.__name__, str(ref._data))
  427. if ref and ref_id not in _refs:
  428. _refs.append(ref_id)
  429. kwargs["_refs"] = _refs
  430. ref.save(**kwargs)
  431. ref._changed_fields = []
  432. @property
  433. def _qs(self):
  434. """Return the queryset to use for updating / reloading / deletions."""
  435. if not hasattr(self, '__objects'):
  436. self.__objects = QuerySet(self, self._get_collection())
  437. return self.__objects
  438. @property
  439. def _object_key(self):
  440. """Get the query dict that can be used to fetch this object from
  441. the database. Most of the time it's a simple PK lookup, but in
  442. case of a sharded collection with a compound shard key, it can
  443. contain a more complex query.
  444. """
  445. select_dict = {'pk': self.pk}
  446. shard_key = self.__class__._meta.get('shard_key', tuple())
  447. for k in shard_key:
  448. path = self._lookup_field(k.split('.'))
  449. actual_key = [p.db_field for p in path]
  450. val = self
  451. for ak in actual_key:
  452. val = getattr(val, ak)
  453. select_dict['__'.join(actual_key)] = val
  454. return select_dict
  455. def update(self, **kwargs):
  456. """Performs an update on the :class:`~mongoengine.Document`
  457. A convenience wrapper to :meth:`~mongoengine.QuerySet.update`.
  458. Raises :class:`OperationError` if called on an object that has not yet
  459. been saved.
  460. """
  461. if self.pk is None:
  462. if kwargs.get('upsert', False):
  463. query = self.to_mongo()
  464. if '_cls' in query:
  465. del query['_cls']
  466. return self._qs.filter(**query).update_one(**kwargs)
  467. else:
  468. raise OperationError(
  469. 'attempt to update a document not yet saved')
  470. # Need to add shard key to query, or you get an error
  471. return self._qs.filter(**self._object_key).update_one(**kwargs)
  472. def delete(self, signal_kwargs=None, **write_concern):
  473. """Delete the :class:`~mongoengine.Document` from the database. This
  474. will only take effect if the document has been previously saved.
  475. :param signal_kwargs: (optional) kwargs dictionary to be passed to
  476. the signal calls.
  477. :param write_concern: Extra keyword arguments are passed down which
  478. will be used as options for the resultant ``getLastError`` command.
  479. For example, ``save(..., w: 2, fsync: True)`` will
  480. wait until at least two servers have recorded the write and
  481. will force an fsync on the primary server.
  482. .. versionchanged:: 0.10.7
  483. Add signal_kwargs argument
  484. """
  485. signal_kwargs = signal_kwargs or {}
  486. signals.pre_delete.send(self.__class__, document=self, **signal_kwargs)
  487. # Delete FileFields separately
  488. FileField = _import_class('FileField')
  489. for name, field in self._fields.iteritems():
  490. if isinstance(field, FileField):
  491. getattr(self, name).delete()
  492. try:
  493. self._qs.filter(
  494. **self._object_key).delete(write_concern=write_concern, _from_doc_delete=True)
  495. except pymongo.errors.OperationFailure as err:
  496. message = u'Could not delete document (%s)' % err.message
  497. raise OperationError(message)
  498. signals.post_delete.send(self.__class__, document=self, **signal_kwargs)
  499. def switch_db(self, db_alias, keep_created=True):
  500. """
  501. Temporarily switch the database for a document instance.
  502. Only really useful for archiving off data and calling `save()`::
  503. user = User.objects.get(id=user_id)
  504. user.switch_db('archive-db')
  505. user.save()
  506. :param str db_alias: The database alias to use for saving the document
  507. :param bool keep_created: keep self._created value after switching db, else is reset to True
  508. .. seealso::
  509. Use :class:`~mongoengine.context_managers.switch_collection`
  510. if you need to read from another collection
  511. """
  512. with switch_db(self.__class__, db_alias) as cls:
  513. collection = cls._get_collection()
  514. db = cls._get_db()
  515. self._get_collection = lambda: collection
  516. self._get_db = lambda: db
  517. self._collection = collection
  518. self._created = True if not keep_created else self._created
  519. self.__objects = self._qs
  520. self.__objects._collection_obj = collection
  521. return self
  522. def switch_collection(self, collection_name, keep_created=True):
  523. """
  524. Temporarily switch the collection for a document instance.
  525. Only really useful for archiving off data and calling `save()`::
  526. user = User.objects.get(id=user_id)
  527. user.switch_collection('old-users')
  528. user.save()
  529. :param str collection_name: The database alias to use for saving the
  530. document
  531. :param bool keep_created: keep self._created value after switching collection, else is reset to True
  532. .. seealso::
  533. Use :class:`~mongoengine.context_managers.switch_db`
  534. if you need to read from another database
  535. """
  536. with switch_collection(self.__class__, collection_name) as cls:
  537. collection = cls._get_collection()
  538. self._get_collection = lambda: collection
  539. self._collection = collection
  540. self._created = True if not keep_created else self._created
  541. self.__objects = self._qs
  542. self.__objects._collection_obj = collection
  543. return self
  544. def select_related(self, max_depth=1):
  545. """Handles dereferencing of :class:`~bson.dbref.DBRef` objects to
  546. a maximum depth in order to cut down the number queries to mongodb.
  547. .. versionadded:: 0.5
  548. """
  549. DeReference = _import_class('DeReference')
  550. DeReference()([self], max_depth + 1)
  551. return self
  552. def reload(self, *fields, **kwargs):
  553. """Reloads all attributes from the database.
  554. :param fields: (optional) args list of fields to reload
  555. :param max_depth: (optional) depth of dereferencing to follow
  556. .. versionadded:: 0.1.2
  557. .. versionchanged:: 0.6 Now chainable
  558. .. versionchanged:: 0.9 Can provide specific fields to reload
  559. """
  560. max_depth = 1
  561. if fields and isinstance(fields[0], int):
  562. max_depth = fields[0]
  563. fields = fields[1:]
  564. elif 'max_depth' in kwargs:
  565. max_depth = kwargs['max_depth']
  566. if self.pk is None:
  567. raise self.DoesNotExist('Document does not exist')
  568. obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
  569. **self._object_key).only(*fields).limit(
  570. 1).select_related(max_depth=max_depth)
  571. if obj:
  572. obj = obj[0]
  573. else:
  574. raise self.DoesNotExist('Document does not exist')
  575. for field in obj._data:
  576. if not fields or field in fields:
  577. try:
  578. setattr(self, field, self._reload(field, obj[field]))
  579. except (KeyError, AttributeError):
  580. try:
  581. # If field is a special field, e.g. items is stored as _reserved_items,
  582. # a KeyError is thrown. So try to retrieve the field from _data
  583. setattr(self, field, self._reload(field, obj._data.get(field)))
  584. except KeyError:
  585. # If field is removed from the database while the object
  586. # is in memory, a reload would cause a KeyError
  587. # i.e. obj.update(unset__field=1) followed by obj.reload()
  588. delattr(self, field)
  589. self._changed_fields = list(
  590. set(self._changed_fields) - set(fields)
  591. ) if fields else obj._changed_fields
  592. self._created = False
  593. return self
  594. def _reload(self, key, value):
  595. """Used by :meth:`~mongoengine.Document.reload` to ensure the
  596. correct instance is linked to self.
  597. """
  598. if isinstance(value, BaseDict):
  599. value = [(k, self._reload(k, v)) for k, v in value.items()]
  600. value = BaseDict(value, self, key)
  601. elif isinstance(value, EmbeddedDocumentList):
  602. value = [self._reload(key, v) for v in value]
  603. value = EmbeddedDocumentList(value, self, key)
  604. elif isinstance(value, BaseList):
  605. value = [self._reload(key, v) for v in value]
  606. value = BaseList(value, self, key)
  607. elif isinstance(value, (EmbeddedDocument, DynamicEmbeddedDocument)):
  608. value._instance = None
  609. value._changed_fields = []
  610. return value
  611. def to_dbref(self):
  612. """Returns an instance of :class:`~bson.dbref.DBRef` useful in
  613. `__raw__` queries."""
  614. if self.pk is None:
  615. msg = 'Only saved documents can have a valid dbref'
  616. raise OperationError(msg)
  617. return DBRef(self.__class__._get_collection_name(), self.pk)
  618. @classmethod
  619. def register_delete_rule(cls, document_cls, field_name, rule):
  620. """This method registers the delete rules to apply when removing this
  621. object.
  622. """
  623. classes = [get_document(class_name)
  624. for class_name in cls._subclasses
  625. if class_name != cls.__name__] + [cls]
  626. documents = [get_document(class_name)
  627. for class_name in document_cls._subclasses
  628. if class_name != document_cls.__name__] + [document_cls]
  629. for klass in classes:
  630. for document_cls in documents:
  631. delete_rules = klass._meta.get('delete_rules') or {}
  632. delete_rules[(document_cls, field_name)] = rule
  633. klass._meta['delete_rules'] = delete_rules
  634. @classmethod
  635. def drop_collection(cls):
  636. """Drops the entire collection associated with this
  637. :class:`~mongoengine.Document` type from the database.
  638. Raises :class:`OperationError` if the document has no collection set
  639. (i.g. if it is `abstract`)
  640. .. versionchanged:: 0.10.7
  641. :class:`OperationError` exception raised if no collection available
  642. """
  643. col_name = cls._get_collection_name()
  644. if not col_name:
  645. raise OperationError('Document %s has no collection defined '
  646. '(is it abstract ?)' % cls)
  647. cls._collection = None
  648. db = cls._get_db()
  649. db.drop_collection(col_name)
  650. @classmethod
  651. def create_index(cls, keys, background=False, **kwargs):
  652. """Creates the given indexes if required.
  653. :param keys: a single index key or a list of index keys (to
  654. construct a multi-field index); keys may be prefixed with a **+**
  655. or a **-** to determine the index ordering
  656. :param background: Allows index creation in the background
  657. """
  658. index_spec = cls._build_index_spec(keys)
  659. index_spec = index_spec.copy()
  660. fields = index_spec.pop('fields')
  661. drop_dups = kwargs.get('drop_dups', False)
  662. if IS_PYMONGO_3 and drop_dups:
  663. msg = 'drop_dups is deprecated and is removed when using PyMongo 3+.'
  664. warnings.warn(msg, DeprecationWarning)
  665. elif not IS_PYMONGO_3:
  666. index_spec['drop_dups'] = drop_dups
  667. index_spec['background'] = background
  668. index_spec.update(kwargs)
  669. if IS_PYMONGO_3:
  670. return cls._get_collection().create_index(fields, **index_spec)
  671. else:
  672. return cls._get_collection().ensure_index(fields, **index_spec)
  673. @classmethod
  674. def ensure_index(cls, key_or_list, drop_dups=False, background=False,
  675. **kwargs):
  676. """Ensure that the given indexes are in place. Deprecated in favour
  677. of create_index.
  678. :param key_or_list: a single index key or a list of index keys (to
  679. construct a multi-field index); keys may be prefixed with a **+**
  680. or a **-** to determine the index ordering
  681. :param background: Allows index creation in the background
  682. :param drop_dups: Was removed/ignored with MongoDB >2.7.5. The value
  683. will be removed if PyMongo3+ is used
  684. """
  685. if IS_PYMONGO_3 and drop_dups:
  686. msg = 'drop_dups is deprecated and is removed when using PyMongo 3+.'
  687. warnings.warn(msg, DeprecationWarning)
  688. elif not IS_PYMONGO_3:
  689. kwargs.update({'drop_dups': drop_dups})
  690. return cls.create_index(key_or_list, background=background, **kwargs)
  691. @classmethod
  692. def ensure_indexes(cls):
  693. """Checks the document meta data and ensures all the indexes exist.
  694. Global defaults can be set in the meta - see :doc:`guide/defining-documents`
  695. .. note:: You can disable automatic index creation by setting
  696. `auto_create_index` to False in the documents meta data
  697. """
  698. background = cls._meta.get('index_background', False)
  699. drop_dups = cls._meta.get('index_drop_dups', False)
  700. index_opts = cls._meta.get('index_opts') or {}
  701. index_cls = cls._meta.get('index_cls', True)
  702. if IS_PYMONGO_3 and drop_dups:
  703. msg = 'drop_dups is deprecated and is removed when using PyMongo 3+.'
  704. warnings.warn(msg, DeprecationWarning)
  705. collection = cls._get_collection()
  706. # 746: when connection is via mongos, the read preference is not necessarily an indication that
  707. # this code runs on a secondary
  708. if not collection.is_mongos and collection.read_preference > 1:
  709. return
  710. # determine if an index which we are creating includes
  711. # _cls as its first field; if so, we can avoid creating
  712. # an extra index on _cls, as mongodb will use the existing
  713. # index to service queries against _cls
  714. cls_indexed = False
  715. # Ensure document-defined indexes are created
  716. if cls._meta['index_specs']:
  717. index_spec = cls._meta['index_specs']
  718. for spec in index_spec:
  719. spec = spec.copy()
  720. fields = spec.pop('fields')
  721. cls_indexed = cls_indexed or includes_cls(fields)
  722. opts = index_opts.copy()
  723. opts.update(spec)
  724. # we shouldn't pass 'cls' to the collection.ensureIndex options
  725. # because of https://jira.mongodb.org/browse/SERVER-769
  726. if 'cls' in opts:
  727. del opts['cls']
  728. if IS_PYMONGO_3:
  729. collection.create_index(fields, background=background, **opts)
  730. else:
  731. collection.ensure_index(fields, background=background,
  732. drop_dups=drop_dups, **opts)
  733. # If _cls is being used (for polymorphism), it needs an index,
  734. # only if another index doesn't begin with _cls
  735. if index_cls and not cls_indexed and cls._meta.get('allow_inheritance'):
  736. # we shouldn't pass 'cls' to the collection.ensureIndex options
  737. # because of https://jira.mongodb.org/browse/SERVER-769
  738. if 'cls' in index_opts:
  739. del index_opts['cls']
  740. if IS_PYMONGO_3:
  741. collection.create_index('_cls', background=background,
  742. **index_opts)
  743. else:
  744. collection.ensure_index('_cls', background=background,
  745. **index_opts)
  746. @classmethod
  747. def list_indexes(cls):
  748. """ Lists all of the indexes that should be created for given
  749. collection. It includes all the indexes from super- and sub-classes.
  750. """
  751. if cls._meta.get('abstract'):
  752. return []
  753. # get all the base classes, subclasses and siblings
  754. classes = []
  755. def get_classes(cls):
  756. if (cls not in classes and
  757. isinstance(cls, TopLevelDocumentMetaclass)):
  758. classes.append(cls)
  759. for base_cls in cls.__bases__:
  760. if (isinstance(base_cls, TopLevelDocumentMetaclass) and
  761. base_cls != Document and
  762. not base_cls._meta.get('abstract') and
  763. base_cls._get_collection().full_name == cls._get_collection().full_name and
  764. base_cls not in classes):
  765. classes.append(base_cls)
  766. get_classes(base_cls)
  767. for subclass in cls.__subclasses__():
  768. if (isinstance(base_cls, TopLevelDocumentMetaclass) and
  769. subclass._get_collection().full_name == cls._get_collection().full_name and
  770. subclass not in classes):
  771. classes.append(subclass)
  772. get_classes(subclass)
  773. get_classes(cls)
  774. # get the indexes spec for all of the gathered classes
  775. def get_indexes_spec(cls):
  776. indexes = []
  777. if cls._meta['index_specs']:
  778. index_spec = cls._meta['index_specs']
  779. for spec in index_spec:
  780. spec = spec.copy()
  781. fields = spec.pop('fields')
  782. indexes.append(fields)
  783. return indexes
  784. indexes = []
  785. for klass in classes:
  786. for index in get_indexes_spec(klass):
  787. if index not in indexes:
  788. indexes.append(index)
  789. # finish up by appending { '_id': 1 } and { '_cls': 1 }, if needed
  790. if [(u'_id', 1)] not in indexes:
  791. indexes.append([(u'_id', 1)])
  792. if cls._meta.get('index_cls', True) and cls._meta.get('allow_inheritance'):
  793. indexes.append([(u'_cls', 1)])
  794. return indexes
  795. @classmethod
  796. def compare_indexes(cls):
  797. """ Compares the indexes defined in MongoEngine with the ones
  798. existing in the database. Returns any missing/extra indexes.
  799. """
  800. required = cls.list_indexes()
  801. existing = []
  802. for info in cls._get_collection().index_information().values():
  803. if '_fts' in info['key'][0]:
  804. index_type = info['key'][0][1]
  805. text_index_fields = info.get('weights').keys()
  806. existing.append(
  807. [(key, index_type) for key in text_index_fields])
  808. else:
  809. existing.append(info['key'])
  810. missing = [index for index in required if index not in existing]
  811. extra = [index for index in existing if index not in required]
  812. # if { _cls: 1 } is missing, make sure it's *really* necessary
  813. if [(u'_cls', 1)] in missing:
  814. cls_obsolete = False
  815. for index in existing:
  816. if includes_cls(index) and index not in extra:
  817. cls_obsolete = True
  818. break
  819. if cls_obsolete:
  820. missing.remove([(u'_cls', 1)])
  821. return {'missing': missing, 'extra': extra}
  822. class DynamicDocument(six.with_metaclass(TopLevelDocumentMetaclass, Document)):
  823. """A Dynamic Document class allowing flexible, expandable and uncontrolled
  824. schemas. As a :class:`~mongoengine.Document` subclass, acts in the same
  825. way as an ordinary document but has expanded style properties. Any data
  826. passed or set against the :class:`~mongoengine.DynamicDocument` that is
  827. not a field is automatically converted into a
  828. :class:`~mongoengine.fields.DynamicField` and data can be attributed to that
  829. field.
  830. .. note::
  831. There is one caveat on Dynamic Documents: fields cannot start with `_`
  832. """
  833. # The __metaclass__ attribute is removed by 2to3 when running with Python3
  834. # my_metaclass is defined so that metaclass can be queried in Python 2 & 3
  835. my_metaclass = TopLevelDocumentMetaclass
  836. _dynamic = True
  837. def __delattr__(self, *args, **kwargs):
  838. """Delete the attribute by setting to None and allowing _delta
  839. to unset it.
  840. """
  841. field_name = args[0]
  842. if field_name in self._dynamic_fields:
  843. setattr(self, field_name, None)
  844. self._dynamic_fields[field_name].null = False
  845. else:
  846. super(DynamicDocument, self).__delattr__(*args, **kwargs)
  847. class DynamicEmbeddedDocument(six.with_metaclass(DocumentMetaclass, EmbeddedDocument)):
  848. """A Dynamic Embedded Document class allowing flexible, expandable and
  849. uncontrolled schemas. See :class:`~mongoengine.DynamicDocument` for more
  850. information about dynamic documents.
  851. """
  852. # The __metaclass__ attribute is removed by 2to3 when running with Python3
  853. # my_metaclass is defined so that metaclass can be queried in Python 2 & 3
  854. my_metaclass = DocumentMetaclass
  855. _dynamic = True
  856. def __delattr__(self, *args, **kwargs):
  857. """Delete the attribute by setting to None and allowing _delta
  858. to unset it.
  859. """
  860. field_name = args[0]
  861. if field_name in self._fields:
  862. default = self._fields[field_name].default
  863. if callable(default):
  864. default = default()
  865. setattr(self, field_name, default)
  866. else:
  867. setattr(self, field_name, None)
  868. class MapReduceDocument(object):
  869. """A document returned from a map/reduce query.
  870. :param collection: An instance of :class:`~pymongo.Collection`
  871. :param key: Document/result key, often an instance of
  872. :class:`~bson.objectid.ObjectId`. If supplied as
  873. an ``ObjectId`` found in the given ``collection``,
  874. the object can be accessed via the ``object`` property.
  875. :param value: The result(s) for this key.
  876. .. versionadded:: 0.3
  877. """
  878. def __init__(self, document, collection, key, value):
  879. self._document = document
  880. self._collection = collection
  881. self.key = key
  882. self.value = value
  883. @property
  884. def object(self):
  885. """Lazy-load the object referenced by ``self.key``. ``self.key``
  886. should be the ``primary_key``.
  887. """
  888. id_field = self._document()._meta['id_field']
  889. id_field_type = type(id_field)
  890. if not isinstance(self.key, id_field_type):
  891. try:
  892. self.key = id_field_type(self.key)
  893. except Exception:
  894. raise Exception('Could not cast key as %s' %
  895. id_field_type.__name__)
  896. if not hasattr(self, '_key_object'):
  897. self._key_object = self._document.objects.with_id(self.key)
  898. return self._key_object
  899. return self._key_object