document.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. import copy
  2. import numbers
  3. from functools import partial
  4. from bson import ObjectId, json_util
  5. from bson.dbref import DBRef
  6. from bson.son import SON
  7. import pymongo
  8. import six
  9. from mongoengine import signals
  10. from mongoengine.base.common import get_document
  11. from mongoengine.base.datastructures import (BaseDict, BaseList,
  12. EmbeddedDocumentList,
  13. LazyReference,
  14. StrictDict)
  15. from mongoengine.base.fields import ComplexBaseField
  16. from mongoengine.common import _import_class
  17. from mongoengine.errors import (FieldDoesNotExist, InvalidDocumentError,
  18. LookUpError, OperationError, ValidationError)
  19. from mongoengine.python_support import Hashable
  20. __all__ = ('BaseDocument', 'NON_FIELD_ERRORS')
  21. NON_FIELD_ERRORS = '__all__'
  22. class BaseDocument(object):
  23. __slots__ = ('_changed_fields', '_initialised', '_created', '_data',
  24. '_dynamic_fields', '_auto_id_field', '_db_field_map',
  25. '__weakref__')
  26. _dynamic = False
  27. _dynamic_lock = True
  28. STRICT = False
  29. def __init__(self, *args, **values):
  30. """
  31. Initialise a document or embedded document
  32. :param __auto_convert: Try and will cast python objects to Object types
  33. :param values: A dictionary of values for the document
  34. """
  35. self._initialised = False
  36. self._created = True
  37. if args:
  38. # Combine positional arguments with named arguments.
  39. # We only want named arguments.
  40. field = iter(self._fields_ordered)
  41. # If its an automatic id field then skip to the first defined field
  42. if getattr(self, '_auto_id_field', False):
  43. next(field)
  44. for value in args:
  45. name = next(field)
  46. if name in values:
  47. raise TypeError(
  48. 'Multiple values for keyword argument "%s"' % name)
  49. values[name] = value
  50. __auto_convert = values.pop('__auto_convert', True)
  51. # 399: set default values only to fields loaded from DB
  52. __only_fields = set(values.pop('__only_fields', values))
  53. _created = values.pop('_created', True)
  54. signals.pre_init.send(self.__class__, document=self, values=values)
  55. # Check if there are undefined fields supplied to the constructor,
  56. # if so raise an Exception.
  57. if not self._dynamic and (self._meta.get('strict', True) or _created):
  58. _undefined_fields = set(values.keys()) - set(
  59. self._fields.keys() + ['id', 'pk', '_cls', '_text_score'])
  60. if _undefined_fields:
  61. msg = (
  62. 'The fields "{0}" do not exist on the document "{1}"'
  63. ).format(_undefined_fields, self._class_name)
  64. raise FieldDoesNotExist(msg)
  65. if self.STRICT and not self._dynamic:
  66. self._data = StrictDict.create(allowed_keys=self._fields_ordered)()
  67. else:
  68. self._data = {}
  69. self._dynamic_fields = SON()
  70. # Assign default values to instance
  71. for key, field in self._fields.iteritems():
  72. if self._db_field_map.get(key, key) in __only_fields:
  73. continue
  74. value = getattr(self, key, None)
  75. setattr(self, key, value)
  76. # Set passed values after initialisation
  77. if self._dynamic:
  78. dynamic_data = {}
  79. for key, value in values.iteritems():
  80. if key in self._fields or key == '_id':
  81. setattr(self, key, value)
  82. else:
  83. dynamic_data[key] = value
  84. else:
  85. FileField = _import_class('FileField')
  86. for key, value in values.iteritems():
  87. key = self._reverse_db_field_map.get(key, key)
  88. if key in self._fields or key in ('id', 'pk', '_cls'):
  89. if __auto_convert and value is not None:
  90. field = self._fields.get(key)
  91. if field and not isinstance(field, FileField):
  92. value = field.to_python(value)
  93. setattr(self, key, value)
  94. else:
  95. self._data[key] = value
  96. # Set any get_<field>_display methods
  97. self.__set_field_display()
  98. if self._dynamic:
  99. self._dynamic_lock = False
  100. for key, value in dynamic_data.iteritems():
  101. setattr(self, key, value)
  102. # Flag initialised
  103. self._initialised = True
  104. self._created = _created
  105. signals.post_init.send(self.__class__, document=self)
  106. def __delattr__(self, *args, **kwargs):
  107. """Handle deletions of fields"""
  108. field_name = args[0]
  109. if field_name in self._fields:
  110. default = self._fields[field_name].default
  111. if callable(default):
  112. default = default()
  113. setattr(self, field_name, default)
  114. else:
  115. super(BaseDocument, self).__delattr__(*args, **kwargs)
  116. def __setattr__(self, name, value):
  117. # Handle dynamic data only if an initialised dynamic document
  118. if self._dynamic and not self._dynamic_lock:
  119. if not hasattr(self, name) and not name.startswith('_'):
  120. DynamicField = _import_class('DynamicField')
  121. field = DynamicField(db_field=name, null=True)
  122. field.name = name
  123. self._dynamic_fields[name] = field
  124. self._fields_ordered += (name,)
  125. if not name.startswith('_'):
  126. value = self.__expand_dynamic_values(name, value)
  127. # Handle marking data as changed
  128. if name in self._dynamic_fields:
  129. self._data[name] = value
  130. if hasattr(self, '_changed_fields'):
  131. self._mark_as_changed(name)
  132. try:
  133. self__created = self._created
  134. except AttributeError:
  135. self__created = True
  136. if (
  137. self._is_document and
  138. not self__created and
  139. name in self._meta.get('shard_key', tuple()) and
  140. self._data.get(name) != value
  141. ):
  142. msg = 'Shard Keys are immutable. Tried to update %s' % name
  143. raise OperationError(msg)
  144. try:
  145. self__initialised = self._initialised
  146. except AttributeError:
  147. self__initialised = False
  148. # Check if the user has created a new instance of a class
  149. if (self._is_document and self__initialised and
  150. self__created and name == self._meta.get('id_field')):
  151. super(BaseDocument, self).__setattr__('_created', False)
  152. super(BaseDocument, self).__setattr__(name, value)
  153. def __getstate__(self):
  154. data = {}
  155. for k in ('_changed_fields', '_initialised', '_created',
  156. '_dynamic_fields', '_fields_ordered'):
  157. if hasattr(self, k):
  158. data[k] = getattr(self, k)
  159. data['_data'] = self.to_mongo()
  160. return data
  161. def __setstate__(self, data):
  162. if isinstance(data['_data'], SON):
  163. data['_data'] = self.__class__._from_son(data['_data'])._data
  164. for k in ('_changed_fields', '_initialised', '_created', '_data',
  165. '_dynamic_fields'):
  166. if k in data:
  167. setattr(self, k, data[k])
  168. if '_fields_ordered' in data:
  169. if self._dynamic:
  170. setattr(self, '_fields_ordered', data['_fields_ordered'])
  171. else:
  172. _super_fields_ordered = type(self)._fields_ordered
  173. setattr(self, '_fields_ordered', _super_fields_ordered)
  174. dynamic_fields = data.get('_dynamic_fields') or SON()
  175. for k in dynamic_fields.keys():
  176. setattr(self, k, data['_data'].get(k))
  177. def __iter__(self):
  178. return iter(self._fields_ordered)
  179. def __getitem__(self, name):
  180. """Dictionary-style field access, return a field's value if present.
  181. """
  182. try:
  183. if name in self._fields_ordered:
  184. return getattr(self, name)
  185. except AttributeError:
  186. pass
  187. raise KeyError(name)
  188. def __setitem__(self, name, value):
  189. """Dictionary-style field access, set a field's value.
  190. """
  191. # Ensure that the field exists before settings its value
  192. if not self._dynamic and name not in self._fields:
  193. raise KeyError(name)
  194. return setattr(self, name, value)
  195. def __contains__(self, name):
  196. try:
  197. val = getattr(self, name)
  198. return val is not None
  199. except AttributeError:
  200. return False
  201. def __len__(self):
  202. return len(self._data)
  203. def __repr__(self):
  204. try:
  205. u = self.__str__()
  206. except (UnicodeEncodeError, UnicodeDecodeError):
  207. u = '[Bad Unicode data]'
  208. repr_type = str if u is None else type(u)
  209. return repr_type('<%s: %s>' % (self.__class__.__name__, u))
  210. def __str__(self):
  211. # TODO this could be simpler?
  212. if hasattr(self, '__unicode__'):
  213. if six.PY3:
  214. return self.__unicode__()
  215. else:
  216. return six.text_type(self).encode('utf-8')
  217. return six.text_type('%s object' % self.__class__.__name__)
  218. def __eq__(self, other):
  219. if isinstance(other, self.__class__) and hasattr(other, 'id') and other.id is not None:
  220. return self.id == other.id
  221. if isinstance(other, DBRef):
  222. return self._get_collection_name() == other.collection and self.id == other.id
  223. if self.id is None:
  224. return self is other
  225. return False
  226. def __ne__(self, other):
  227. return not self.__eq__(other)
  228. def clean(self):
  229. """
  230. Hook for doing document level data cleaning before validation is run.
  231. Any ValidationError raised by this method will not be associated with
  232. a particular field; it will have a special-case association with the
  233. field defined by NON_FIELD_ERRORS.
  234. """
  235. pass
  236. def get_text_score(self):
  237. """
  238. Get text score from text query
  239. """
  240. if '_text_score' not in self._data:
  241. raise InvalidDocumentError('This document is not originally built from a text query')
  242. return self._data['_text_score']
  243. def to_mongo(self, use_db_field=True, fields=None):
  244. """
  245. Return as SON data ready for use with MongoDB.
  246. """
  247. if not fields:
  248. fields = []
  249. data = SON()
  250. data['_id'] = None
  251. data['_cls'] = self._class_name
  252. # only root fields ['test1.a', 'test2'] => ['test1', 'test2']
  253. root_fields = {f.split('.')[0] for f in fields}
  254. for field_name in self:
  255. if root_fields and field_name not in root_fields:
  256. continue
  257. value = self._data.get(field_name, None)
  258. field = self._fields.get(field_name)
  259. if field is None and self._dynamic:
  260. field = self._dynamic_fields.get(field_name)
  261. if value is not None:
  262. f_inputs = field.to_mongo.__code__.co_varnames
  263. ex_vars = {}
  264. if fields and 'fields' in f_inputs:
  265. key = '%s.' % field_name
  266. embedded_fields = [
  267. i.replace(key, '') for i in fields
  268. if i.startswith(key)]
  269. ex_vars['fields'] = embedded_fields
  270. if 'use_db_field' in f_inputs:
  271. ex_vars['use_db_field'] = use_db_field
  272. value = field.to_mongo(value, **ex_vars)
  273. # Handle self generating fields
  274. if value is None and field._auto_gen:
  275. value = field.generate()
  276. self._data[field_name] = value
  277. if (value is not None) or (field.null):
  278. if use_db_field:
  279. data[field.db_field] = value
  280. else:
  281. data[field.name] = value
  282. # Only add _cls if allow_inheritance is True
  283. if not self._meta.get('allow_inheritance'):
  284. data.pop('_cls')
  285. return data
  286. def validate(self, clean=True):
  287. """Ensure that all fields' values are valid and that required fields
  288. are present.
  289. """
  290. # Ensure that each field is matched to a valid value
  291. errors = {}
  292. if clean:
  293. try:
  294. self.clean()
  295. except ValidationError as error:
  296. errors[NON_FIELD_ERRORS] = error
  297. # Get a list of tuples of field names and their current values
  298. fields = [(self._fields.get(name, self._dynamic_fields.get(name)),
  299. self._data.get(name)) for name in self._fields_ordered]
  300. EmbeddedDocumentField = _import_class('EmbeddedDocumentField')
  301. GenericEmbeddedDocumentField = _import_class(
  302. 'GenericEmbeddedDocumentField')
  303. for field, value in fields:
  304. if value is not None:
  305. try:
  306. if isinstance(field, (EmbeddedDocumentField,
  307. GenericEmbeddedDocumentField)):
  308. field._validate(value, clean=clean)
  309. else:
  310. field._validate(value)
  311. except ValidationError as error:
  312. errors[field.name] = error.errors or error
  313. except (ValueError, AttributeError, AssertionError) as error:
  314. errors[field.name] = error
  315. elif field.required and not getattr(field, '_auto_gen', False):
  316. errors[field.name] = ValidationError('Field is required',
  317. field_name=field.name)
  318. if errors:
  319. pk = 'None'
  320. if hasattr(self, 'pk'):
  321. pk = self.pk
  322. elif self._instance and hasattr(self._instance, 'pk'):
  323. pk = self._instance.pk
  324. message = 'ValidationError (%s:%s) ' % (self._class_name, pk)
  325. raise ValidationError(message, errors=errors)
  326. def to_json(self, *args, **kwargs):
  327. """Convert this document to JSON.
  328. :param use_db_field: Serialize field names as they appear in
  329. MongoDB (as opposed to attribute names on this document).
  330. Defaults to True.
  331. """
  332. use_db_field = kwargs.pop('use_db_field', True)
  333. return json_util.dumps(self.to_mongo(use_db_field), *args, **kwargs)
  334. @classmethod
  335. def from_json(cls, json_data, created=False):
  336. """Converts json data to a Document instance
  337. :param json_data: The json data to load into the Document
  338. :param created: If True, the document will be considered as a brand new document
  339. If False and an id is provided, it will consider that the data being
  340. loaded corresponds to what's already in the database (This has an impact of subsequent call to .save())
  341. If False and no id is provided, it will consider the data as a new document
  342. (default ``False``)
  343. """
  344. return cls._from_son(json_util.loads(json_data), created=created)
  345. def __expand_dynamic_values(self, name, value):
  346. """Expand any dynamic values to their correct types / values."""
  347. if not isinstance(value, (dict, list, tuple)):
  348. return value
  349. # If the value is a dict with '_cls' in it, turn it into a document
  350. is_dict = isinstance(value, dict)
  351. if is_dict and '_cls' in value:
  352. cls = get_document(value['_cls'])
  353. return cls(**value)
  354. if is_dict:
  355. value = {
  356. k: self.__expand_dynamic_values(k, v)
  357. for k, v in value.items()
  358. }
  359. else:
  360. value = [self.__expand_dynamic_values(name, v) for v in value]
  361. # Convert lists / values so we can watch for any changes on them
  362. EmbeddedDocumentListField = _import_class('EmbeddedDocumentListField')
  363. if (isinstance(value, (list, tuple)) and
  364. not isinstance(value, BaseList)):
  365. if issubclass(type(self), EmbeddedDocumentListField):
  366. value = EmbeddedDocumentList(value, self, name)
  367. else:
  368. value = BaseList(value, self, name)
  369. elif isinstance(value, dict) and not isinstance(value, BaseDict):
  370. value = BaseDict(value, self, name)
  371. return value
  372. def _mark_as_changed(self, key):
  373. """Mark a key as explicitly changed by the user."""
  374. if not key:
  375. return
  376. if not hasattr(self, '_changed_fields'):
  377. return
  378. if '.' in key:
  379. key, rest = key.split('.', 1)
  380. key = self._db_field_map.get(key, key)
  381. key = '%s.%s' % (key, rest)
  382. else:
  383. key = self._db_field_map.get(key, key)
  384. if key not in self._changed_fields:
  385. levels, idx = key.split('.'), 1
  386. while idx <= len(levels):
  387. if '.'.join(levels[:idx]) in self._changed_fields:
  388. break
  389. idx += 1
  390. else:
  391. self._changed_fields.append(key)
  392. # remove lower level changed fields
  393. level = '.'.join(levels[:idx]) + '.'
  394. remove = self._changed_fields.remove
  395. for field in self._changed_fields[:]:
  396. if field.startswith(level):
  397. remove(field)
  398. def _clear_changed_fields(self):
  399. """Using _get_changed_fields iterate and remove any fields that
  400. are marked as changed.
  401. """
  402. for changed in self._get_changed_fields():
  403. parts = changed.split('.')
  404. data = self
  405. for part in parts:
  406. if isinstance(data, list):
  407. try:
  408. data = data[int(part)]
  409. except IndexError:
  410. data = None
  411. elif isinstance(data, dict):
  412. data = data.get(part, None)
  413. else:
  414. data = getattr(data, part, None)
  415. if not isinstance(data, LazyReference) and hasattr(data, '_changed_fields'):
  416. if getattr(data, '_is_document', False):
  417. continue
  418. data._changed_fields = []
  419. self._changed_fields = []
  420. def _nestable_types_changed_fields(self, changed_fields, base_key, data):
  421. """Inspect nested data for changed fields
  422. :param changed_fields: Previously collected changed fields
  423. :param base_key: The base key that must be used to prepend changes to this data
  424. :param data: data to inspect for changes
  425. """
  426. # Loop list / dict fields as they contain documents
  427. # Determine the iterator to use
  428. if not hasattr(data, 'items'):
  429. iterator = enumerate(data)
  430. else:
  431. iterator = data.iteritems()
  432. for index_or_key, value in iterator:
  433. item_key = '%s%s.' % (base_key, index_or_key)
  434. # don't check anything lower if this key is already marked
  435. # as changed.
  436. if item_key[:-1] in changed_fields:
  437. continue
  438. if hasattr(value, '_get_changed_fields'):
  439. changed = value._get_changed_fields()
  440. changed_fields += ['%s%s' % (item_key, k) for k in changed if k]
  441. elif isinstance(value, (list, tuple, dict)):
  442. self._nestable_types_changed_fields(
  443. changed_fields, item_key, value)
  444. def _get_changed_fields(self):
  445. """Return a list of all fields that have explicitly been changed.
  446. """
  447. EmbeddedDocument = _import_class('EmbeddedDocument')
  448. ReferenceField = _import_class('ReferenceField')
  449. GenericReferenceField = _import_class('GenericReferenceField')
  450. SortedListField = _import_class('SortedListField')
  451. changed_fields = []
  452. changed_fields += getattr(self, '_changed_fields', [])
  453. for field_name in self._fields_ordered:
  454. db_field_name = self._db_field_map.get(field_name, field_name)
  455. key = '%s.' % db_field_name
  456. data = self._data.get(field_name, None)
  457. field = self._fields.get(field_name)
  458. if db_field_name in changed_fields:
  459. # Whole field already marked as changed, no need to go further
  460. continue
  461. if isinstance(field, ReferenceField): # Don't follow referenced documents
  462. continue
  463. if isinstance(data, EmbeddedDocument):
  464. # Find all embedded fields that have been changed
  465. changed = data._get_changed_fields()
  466. changed_fields += ['%s%s' % (key, k) for k in changed if k]
  467. elif isinstance(data, (list, tuple, dict)):
  468. if (hasattr(field, 'field') and
  469. isinstance(field.field, (ReferenceField, GenericReferenceField))):
  470. continue
  471. elif isinstance(field, SortedListField) and field._ordering:
  472. # if ordering is affected whole list is changed
  473. if any(field._ordering in d._changed_fields for d in data):
  474. changed_fields.append(db_field_name)
  475. continue
  476. self._nestable_types_changed_fields(
  477. changed_fields, key, data)
  478. return changed_fields
  479. def _delta(self):
  480. """Returns the delta (set, unset) of the changes for a document.
  481. Gets any values that have been explicitly changed.
  482. """
  483. # Handles cases where not loaded from_son but has _id
  484. doc = self.to_mongo()
  485. set_fields = self._get_changed_fields()
  486. unset_data = {}
  487. parts = []
  488. if hasattr(self, '_changed_fields'):
  489. set_data = {}
  490. # Fetch each set item from its path
  491. for path in set_fields:
  492. parts = path.split('.')
  493. d = doc
  494. new_path = []
  495. for p in parts:
  496. if isinstance(d, (ObjectId, DBRef)):
  497. break
  498. elif isinstance(d, list) and p.lstrip('-').isdigit():
  499. if p[0] == '-':
  500. p = str(len(d) + int(p))
  501. try:
  502. d = d[int(p)]
  503. except IndexError:
  504. d = None
  505. elif hasattr(d, 'get'):
  506. d = d.get(p)
  507. new_path.append(p)
  508. path = '.'.join(new_path)
  509. set_data[path] = d
  510. else:
  511. set_data = doc
  512. if '_id' in set_data:
  513. del set_data['_id']
  514. # Determine if any changed items were actually unset.
  515. for path, value in set_data.items():
  516. if value or isinstance(value, (numbers.Number, bool)):
  517. continue
  518. # If we've set a value that ain't the default value don't unset it.
  519. default = None
  520. if (self._dynamic and len(parts) and parts[0] in
  521. self._dynamic_fields):
  522. del set_data[path]
  523. unset_data[path] = 1
  524. continue
  525. elif path in self._fields:
  526. default = self._fields[path].default
  527. else: # Perform a full lookup for lists / embedded lookups
  528. d = self
  529. parts = path.split('.')
  530. db_field_name = parts.pop()
  531. for p in parts:
  532. if isinstance(d, list) and p.lstrip('-').isdigit():
  533. if p[0] == '-':
  534. p = str(len(d) + int(p))
  535. d = d[int(p)]
  536. elif (hasattr(d, '__getattribute__') and
  537. not isinstance(d, dict)):
  538. real_path = d._reverse_db_field_map.get(p, p)
  539. d = getattr(d, real_path)
  540. else:
  541. d = d.get(p)
  542. if hasattr(d, '_fields'):
  543. field_name = d._reverse_db_field_map.get(db_field_name,
  544. db_field_name)
  545. if field_name in d._fields:
  546. default = d._fields.get(field_name).default
  547. else:
  548. default = None
  549. if default is not None:
  550. if callable(default):
  551. default = default()
  552. if default != value:
  553. continue
  554. del set_data[path]
  555. unset_data[path] = 1
  556. return set_data, unset_data
  557. @classmethod
  558. def _get_collection_name(cls):
  559. """Return the collection name for this class. None for abstract
  560. class.
  561. """
  562. return cls._meta.get('collection', None)
  563. @classmethod
  564. def _from_son(cls, son, _auto_dereference=True, only_fields=None, created=False):
  565. """Create an instance of a Document (subclass) from a PyMongo
  566. SON.
  567. """
  568. if not only_fields:
  569. only_fields = []
  570. if son and not isinstance(son, dict):
  571. raise ValueError("The source SON object needs to be of type 'dict'")
  572. # Get the class name from the document, falling back to the given
  573. # class if unavailable
  574. class_name = son.get('_cls', cls._class_name)
  575. # Convert SON to a data dict, making sure each key is a string and
  576. # corresponds to the right db field.
  577. data = {}
  578. for key, value in son.iteritems():
  579. key = str(key)
  580. key = cls._db_field_map.get(key, key)
  581. data[key] = value
  582. # Return correct subclass for document type
  583. if class_name != cls._class_name:
  584. cls = get_document(class_name)
  585. changed_fields = []
  586. errors_dict = {}
  587. fields = cls._fields
  588. if not _auto_dereference:
  589. fields = copy.deepcopy(fields)
  590. for field_name, field in fields.iteritems():
  591. field._auto_dereference = _auto_dereference
  592. if field.db_field in data:
  593. value = data[field.db_field]
  594. try:
  595. data[field_name] = (value if value is None
  596. else field.to_python(value))
  597. if field_name != field.db_field:
  598. del data[field.db_field]
  599. except (AttributeError, ValueError) as e:
  600. errors_dict[field_name] = e
  601. if errors_dict:
  602. errors = '\n'.join(['%s - %s' % (k, v)
  603. for k, v in errors_dict.items()])
  604. msg = ('Invalid data to create a `%s` instance.\n%s'
  605. % (cls._class_name, errors))
  606. raise InvalidDocumentError(msg)
  607. # In STRICT documents, remove any keys that aren't in cls._fields
  608. if cls.STRICT:
  609. data = {k: v for k, v in data.iteritems() if k in cls._fields}
  610. try:
  611. obj = cls(__auto_convert = False, _created = created, __only_fields = only_fields, **data)
  612. obj._changed_fields = changed_fields
  613. if not _auto_dereference:
  614. obj._fields = fields
  615. except Exception as e:
  616. raise e
  617. return obj
  618. @classmethod
  619. def _build_index_specs(cls, meta_indexes):
  620. """Generate and merge the full index specs."""
  621. geo_indices = cls._geo_indices()
  622. unique_indices = cls._unique_with_indexes()
  623. index_specs = [cls._build_index_spec(spec) for spec in meta_indexes]
  624. def merge_index_specs(index_specs, indices):
  625. """Helper method for merging index specs."""
  626. if not indices:
  627. return index_specs
  628. # Create a map of index fields to index spec. We're converting
  629. # the fields from a list to a tuple so that it's hashable.
  630. spec_fields = {
  631. tuple(index['fields']): index for index in index_specs
  632. }
  633. # For each new index, if there's an existing index with the same
  634. # fields list, update the existing spec with all data from the
  635. # new spec.
  636. for new_index in indices:
  637. candidate = spec_fields.get(tuple(new_index['fields']))
  638. if candidate is None:
  639. index_specs.append(new_index)
  640. else:
  641. candidate.update(new_index)
  642. return index_specs
  643. # Merge geo indexes and unique_with indexes into the meta index specs.
  644. index_specs = merge_index_specs(index_specs, geo_indices)
  645. index_specs = merge_index_specs(index_specs, unique_indices)
  646. return index_specs
  647. @classmethod
  648. def _build_index_spec(cls, spec):
  649. """Build a PyMongo index spec from a MongoEngine index spec."""
  650. if isinstance(spec, six.string_types):
  651. spec = {'fields': [spec]}
  652. elif isinstance(spec, (list, tuple)):
  653. spec = {'fields': list(spec)}
  654. elif isinstance(spec, dict):
  655. spec = dict(spec)
  656. index_list = []
  657. direction = None
  658. # Check to see if we need to include _cls
  659. allow_inheritance = cls._meta.get('allow_inheritance')
  660. include_cls = (
  661. allow_inheritance and
  662. not spec.get('sparse', False) and
  663. spec.get('cls', True) and
  664. '_cls' not in spec['fields']
  665. )
  666. # 733: don't include cls if index_cls is False unless there is an explicit cls with the index
  667. include_cls = include_cls and (spec.get('cls', False) or cls._meta.get('index_cls', True))
  668. if 'cls' in spec:
  669. spec.pop('cls')
  670. for key in spec['fields']:
  671. # If inherited spec continue
  672. if isinstance(key, (list, tuple)):
  673. continue
  674. # ASCENDING from +
  675. # DESCENDING from -
  676. # TEXT from $
  677. # HASHED from #
  678. # GEOSPHERE from (
  679. # GEOHAYSTACK from )
  680. # GEO2D from *
  681. direction = pymongo.ASCENDING
  682. if key.startswith('-'):
  683. direction = pymongo.DESCENDING
  684. elif key.startswith('$'):
  685. direction = pymongo.TEXT
  686. elif key.startswith('#'):
  687. direction = pymongo.HASHED
  688. elif key.startswith('('):
  689. direction = pymongo.GEOSPHERE
  690. elif key.startswith(')'):
  691. direction = pymongo.GEOHAYSTACK
  692. elif key.startswith('*'):
  693. direction = pymongo.GEO2D
  694. if key.startswith(('+', '-', '*', '$', '#', '(', ')')):
  695. key = key[1:]
  696. # Use real field name, do it manually because we need field
  697. # objects for the next part (list field checking)
  698. parts = key.split('.')
  699. if parts in (['pk'], ['id'], ['_id']):
  700. key = '_id'
  701. else:
  702. fields = cls._lookup_field(parts)
  703. parts = []
  704. for field in fields:
  705. try:
  706. if field != '_id':
  707. field = field.db_field
  708. except AttributeError:
  709. pass
  710. parts.append(field)
  711. key = '.'.join(parts)
  712. index_list.append((key, direction))
  713. # Don't add cls to a geo index
  714. if include_cls and direction not in (
  715. pymongo.GEO2D, pymongo.GEOHAYSTACK, pymongo.GEOSPHERE):
  716. index_list.insert(0, ('_cls', 1))
  717. if index_list:
  718. spec['fields'] = index_list
  719. return spec
  720. @classmethod
  721. def _unique_with_indexes(cls, namespace=''):
  722. """Find unique indexes in the document schema and return them."""
  723. unique_indexes = []
  724. for field_name, field in cls._fields.items():
  725. sparse = field.sparse
  726. # Generate a list of indexes needed by uniqueness constraints
  727. if field.unique:
  728. unique_fields = [field.db_field]
  729. # Add any unique_with fields to the back of the index spec
  730. if field.unique_with:
  731. if isinstance(field.unique_with, six.string_types):
  732. field.unique_with = [field.unique_with]
  733. # Convert unique_with field names to real field names
  734. unique_with = []
  735. for other_name in field.unique_with:
  736. parts = other_name.split('.')
  737. # Lookup real name
  738. parts = cls._lookup_field(parts)
  739. name_parts = [part.db_field for part in parts]
  740. unique_with.append('.'.join(name_parts))
  741. # Unique field should be required
  742. parts[-1].required = True
  743. sparse = (not sparse and
  744. parts[-1].name not in cls.__dict__)
  745. unique_fields += unique_with
  746. # Add the new index to the list
  747. fields = [
  748. ('%s%s' % (namespace, f), pymongo.ASCENDING)
  749. for f in unique_fields
  750. ]
  751. index = {'fields': fields, 'unique': True, 'sparse': sparse}
  752. unique_indexes.append(index)
  753. if field.__class__.__name__ == 'ListField':
  754. field = field.field
  755. # Grab any embedded document field unique indexes
  756. if (field.__class__.__name__ == 'EmbeddedDocumentField' and
  757. field.document_type != cls):
  758. field_namespace = '%s.' % field_name
  759. doc_cls = field.document_type
  760. unique_indexes += doc_cls._unique_with_indexes(field_namespace)
  761. return unique_indexes
  762. @classmethod
  763. def _geo_indices(cls, inspected=None, parent_field=None):
  764. inspected = inspected or []
  765. geo_indices = []
  766. inspected.append(cls)
  767. geo_field_type_names = ('EmbeddedDocumentField', 'GeoPointField',
  768. 'PointField', 'LineStringField',
  769. 'PolygonField')
  770. geo_field_types = tuple([_import_class(field)
  771. for field in geo_field_type_names])
  772. for field in cls._fields.values():
  773. if not isinstance(field, geo_field_types):
  774. continue
  775. if hasattr(field, 'document_type'):
  776. field_cls = field.document_type
  777. if field_cls in inspected:
  778. continue
  779. if hasattr(field_cls, '_geo_indices'):
  780. geo_indices += field_cls._geo_indices(
  781. inspected, parent_field=field.db_field)
  782. elif field._geo_index:
  783. field_name = field.db_field
  784. if parent_field:
  785. field_name = '%s.%s' % (parent_field, field_name)
  786. geo_indices.append({
  787. 'fields': [(field_name, field._geo_index)]
  788. })
  789. return geo_indices
  790. @classmethod
  791. def _lookup_field(cls, parts):
  792. """Given the path to a given field, return a list containing
  793. the Field object associated with that field and all of its parent
  794. Field objects.
  795. Args:
  796. parts (str, list, or tuple) - path to the field. Should be a
  797. string for simple fields existing on this document or a list
  798. of strings for a field that exists deeper in embedded documents.
  799. Returns:
  800. A list of Field instances for fields that were found or
  801. strings for sub-fields that weren't.
  802. Example:
  803. >>> user._lookup_field('name')
  804. [<mongoengine.fields.StringField at 0x1119bff50>]
  805. >>> user._lookup_field('roles')
  806. [<mongoengine.fields.EmbeddedDocumentListField at 0x1119ec250>]
  807. >>> user._lookup_field(['roles', 'role'])
  808. [<mongoengine.fields.EmbeddedDocumentListField at 0x1119ec250>,
  809. <mongoengine.fields.StringField at 0x1119ec050>]
  810. >>> user._lookup_field('doesnt_exist')
  811. raises LookUpError
  812. >>> user._lookup_field(['roles', 'doesnt_exist'])
  813. [<mongoengine.fields.EmbeddedDocumentListField at 0x1119ec250>,
  814. 'doesnt_exist']
  815. """
  816. # TODO this method is WAY too complicated. Simplify it.
  817. # TODO don't think returning a string for embedded non-existent fields is desired
  818. ListField = _import_class('ListField')
  819. DynamicField = _import_class('DynamicField')
  820. if not isinstance(parts, (list, tuple)):
  821. parts = [parts]
  822. fields = []
  823. field = None
  824. for field_name in parts:
  825. # Handle ListField indexing:
  826. if field_name.isdigit() and isinstance(field, ListField):
  827. fields.append(field_name)
  828. continue
  829. # Look up first field from the document
  830. if field is None:
  831. if field_name == 'pk':
  832. # Deal with "primary key" alias
  833. field_name = cls._meta['id_field']
  834. if field_name in cls._fields:
  835. field = cls._fields[field_name]
  836. elif cls._dynamic:
  837. field = DynamicField(db_field=field_name)
  838. elif cls._meta.get('allow_inheritance') or cls._meta.get('abstract', False):
  839. # 744: in case the field is defined in a subclass
  840. for subcls in cls.__subclasses__():
  841. try:
  842. field = subcls._lookup_field([field_name])[0]
  843. except LookUpError:
  844. continue
  845. if field is not None:
  846. break
  847. else:
  848. raise LookUpError('Cannot resolve field "%s"' % field_name)
  849. else:
  850. raise LookUpError('Cannot resolve field "%s"' % field_name)
  851. else:
  852. ReferenceField = _import_class('ReferenceField')
  853. GenericReferenceField = _import_class('GenericReferenceField')
  854. # If previous field was a reference, throw an error (we
  855. # cannot look up fields that are on references).
  856. if isinstance(field, (ReferenceField, GenericReferenceField)):
  857. raise LookUpError('Cannot perform join in mongoDB: %s' %
  858. '__'.join(parts))
  859. # If the parent field has a "field" attribute which has a
  860. # lookup_member method, call it to find the field
  861. # corresponding to this iteration.
  862. if hasattr(getattr(field, 'field', None), 'lookup_member'):
  863. new_field = field.field.lookup_member(field_name)
  864. # If the parent field is a DynamicField or if it's part of
  865. # a DynamicDocument, mark current field as a DynamicField
  866. # with db_name equal to the field name.
  867. elif cls._dynamic and (isinstance(field, DynamicField) or
  868. getattr(getattr(field, 'document_type', None), '_dynamic', None)):
  869. new_field = DynamicField(db_field=field_name)
  870. # Else, try to use the parent field's lookup_member method
  871. # to find the subfield.
  872. elif hasattr(field, 'lookup_member'):
  873. new_field = field.lookup_member(field_name)
  874. # Raise a LookUpError if all the other conditions failed.
  875. else:
  876. raise LookUpError(
  877. 'Cannot resolve subfield or operator {} '
  878. 'on the field {}'.format(field_name, field.name)
  879. )
  880. # If current field still wasn't found and the parent field
  881. # is a ComplexBaseField, add the name current field name and
  882. # move on.
  883. if not new_field and isinstance(field, ComplexBaseField):
  884. fields.append(field_name)
  885. continue
  886. elif not new_field:
  887. raise LookUpError('Cannot resolve field "%s"' % field_name)
  888. field = new_field # update field to the new field type
  889. fields.append(field)
  890. return fields
  891. @classmethod
  892. def _translate_field_name(cls, field, sep='.'):
  893. """Translate a field attribute name to a database field name.
  894. """
  895. parts = field.split(sep)
  896. parts = [f.db_field for f in cls._lookup_field(parts)]
  897. return '.'.join(parts)
  898. def __set_field_display(self):
  899. """For each field that specifies choices, create a
  900. get_<field>_display method.
  901. """
  902. fields_with_choices = [(n, f) for n, f in self._fields.items()
  903. if f.choices]
  904. for attr_name, field in fields_with_choices:
  905. setattr(self,
  906. 'get_%s_display' % attr_name,
  907. partial(self.__get_field_display, field=field))
  908. def __get_field_display(self, field):
  909. """Return the display value for a choice field"""
  910. value = getattr(self, field.name)
  911. if field.choices and isinstance(field.choices[0], (list, tuple)):
  912. if value is None:
  913. return None
  914. sep = getattr(field, 'display_sep', ' ')
  915. values = value if field.__class__.__name__ in ('ListField', 'SortedListField') else [value]
  916. return sep.join([
  917. six.text_type(dict(field.choices).get(val, val))
  918. for val in values or []])
  919. return value