Convert a MongoDB-compatible type to a Python type.
(self, value)
| 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.""" |
nothing calls this directly
no test coverage detected