MCPcopy Index your code
hub / github.com/MongoEngine/mongoengine / to_python

Method to_python

mongoengine/base/fields.py:404–452  ·  view source on GitHub ↗

Convert a MongoDB-compatible type to a Python type.

(self, value)

Source from the content-addressed store, hash-verified

402 return value
403
404 def to_python(self, value):
405 """Convert a MongoDB-compatible type to a Python type."""
406 if isinstance(value, str):
407 return value
408
409 if hasattr(value, "to_python"):
410 return value.to_python()
411
412 BaseDocument = _import_class("BaseDocument")
413 if isinstance(value, BaseDocument):
414 # Something is wrong, return the value as it is
415 return value
416
417 is_list = False
418 if not hasattr(value, "items"):
419 try:
420 is_list = True
421 value = {idx: v for idx, v in enumerate(value)}
422 except TypeError: # Not iterable return the value
423 return value
424
425 if self.field:
426 self.field.set_auto_dereferencing(self._auto_dereference)
427 value_dict = {
428 key: self.field.to_python(item) for key, item in value.items()
429 }
430 else:
431 Document = _import_class("Document")
432 value_dict = {}
433 for k, v in value.items():
434 if isinstance(v, Document):
435 # We need the id from the saved object to create the DBRef
436 if v.pk is None:
437 self.error(
438 "You can only reference documents once they"
439 " have been saved to the database"
440 )
441 collection = v._get_collection_name()
442 value_dict[k] = DBRef(collection, v.pk)
443 elif hasattr(v, "to_python"):
444 value_dict[k] = v.to_python()
445 else:
446 value_dict[k] = self.to_python(v)
447
448 if is_list: # Convert back to a list
449 return [
450 v for _, v in sorted(value_dict.items(), key=operator.itemgetter(0))
451 ]
452 return value_dict
453
454 def to_mongo(self, value, use_db_field=True, fields=None):
455 """Convert a Python type to a MongoDB-compatible type."""

Callers

nothing calls this directly

Calls 6

_import_classFunction · 0.90
itemsMethod · 0.80
errorMethod · 0.80
to_pythonMethod · 0.45
_get_collection_nameMethod · 0.45

Tested by

no test coverage detected