Convert a Python type to a MongoDB-compatible type.
(self, value, use_db_field=True, fields=None)
| 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.""" |
| 456 | Document = _import_class("Document") |
| 457 | EmbeddedDocument = _import_class("EmbeddedDocument") |
| 458 | GenericReferenceField = _import_class("GenericReferenceField") |
| 459 | |
| 460 | if isinstance(value, str): |
| 461 | return value |
| 462 | |
| 463 | if hasattr(value, "to_mongo"): |
| 464 | if isinstance(value, Document): |
| 465 | return GenericReferenceField().to_mongo(value) |
| 466 | cls = value.__class__ |
| 467 | val = value.to_mongo(use_db_field, fields) |
| 468 | # If it's a document that is not inherited add _cls |
| 469 | if isinstance(value, EmbeddedDocument): |
| 470 | val["_cls"] = cls.__name__ |
| 471 | return val |
| 472 | |
| 473 | is_list = False |
| 474 | if not hasattr(value, "items"): |
| 475 | try: |
| 476 | is_list = True |
| 477 | value = {k: v for k, v in enumerate(value)} |
| 478 | except TypeError: # Not iterable return the value |
| 479 | return value |
| 480 | |
| 481 | if self.field: |
| 482 | value_dict = { |
| 483 | key: self.field._to_mongo_safe_call(item, use_db_field, fields) |
| 484 | for key, item in value.items() |
| 485 | } |
| 486 | else: |
| 487 | value_dict = {} |
| 488 | for k, v in value.items(): |
| 489 | if isinstance(v, Document): |
| 490 | # We need the id from the saved object to create the DBRef |
| 491 | if v.pk is None: |
| 492 | self.error( |
| 493 | "You can only reference documents once they" |
| 494 | " have been saved to the database" |
| 495 | ) |
| 496 | |
| 497 | # If it's a document that is not inheritable it won't have |
| 498 | # any _cls data so make it a generic reference allows |
| 499 | # us to dereference |
| 500 | meta = getattr(v, "_meta", {}) |
| 501 | allow_inheritance = meta.get("allow_inheritance") |
| 502 | if not allow_inheritance: |
| 503 | value_dict[k] = GenericReferenceField().to_mongo(v) |
| 504 | else: |
| 505 | collection = v._get_collection_name() |
| 506 | value_dict[k] = DBRef(collection, v.pk) |
| 507 | elif hasattr(v, "to_mongo"): |
| 508 | cls = v.__class__ |
| 509 | val = v.to_mongo(use_db_field, fields) |
| 510 | # If it's a document that is not inherited add _cls |
| 511 | if isinstance(v, (Document, EmbeddedDocument)): |
no test coverage detected