Convert a Python type to a MongoDB compatible type.
(self, value, use_db_field=True, fields=None)
| 850 | Used by :class:`~mongoengine.DynamicDocument` to handle dynamic data""" |
| 851 | |
| 852 | def to_mongo(self, value, use_db_field=True, fields=None): |
| 853 | """Convert a Python type to a MongoDB compatible type.""" |
| 854 | |
| 855 | if isinstance(value, str): |
| 856 | return value |
| 857 | |
| 858 | if hasattr(value, "to_mongo"): |
| 859 | cls = value.__class__ |
| 860 | val = value.to_mongo(use_db_field, fields) |
| 861 | # If we its a document thats not inherited add _cls |
| 862 | if isinstance(value, Document): |
| 863 | val = {"_ref": value.to_dbref(), "_cls": cls.__name__} |
| 864 | if isinstance(value, EmbeddedDocument): |
| 865 | val["_cls"] = cls.__name__ |
| 866 | return val |
| 867 | |
| 868 | if not isinstance(value, (dict, list, tuple)): |
| 869 | return value |
| 870 | |
| 871 | is_list = False |
| 872 | if not hasattr(value, "items"): |
| 873 | is_list = True |
| 874 | value = {k: v for k, v in enumerate(value)} |
| 875 | |
| 876 | data = {} |
| 877 | for k, v in value.items(): |
| 878 | data[k] = self.to_mongo(v, use_db_field, fields) |
| 879 | |
| 880 | value = data |
| 881 | if is_list: # Convert back to a list |
| 882 | value = [v for k, v in sorted(data.items(), key=itemgetter(0))] |
| 883 | return value |
| 884 | |
| 885 | def to_python(self, value): |
| 886 | if isinstance(value, dict) and "_cls" in value: |
no test coverage detected