Special version of JSONDictField which takes care of compatibility between old EscapedDictField and EscapedDynamicField format and the new one. On retrieval, if an old format is detected it's correctly un-serialized and on insertion, we always insert data in a new format.
| 511 | |
| 512 | |
| 513 | class JSONDictEscapedFieldCompatibilityField(JSONDictField): |
| 514 | """ |
| 515 | Special version of JSONDictField which takes care of compatibility between old EscapedDictField |
| 516 | and EscapedDynamicField format and the new one. |
| 517 | |
| 518 | On retrieval, if an old format is detected it's correctly un-serialized and on insertion, we |
| 519 | always insert data in a new format. |
| 520 | """ |
| 521 | |
| 522 | def to_mongo(self, value): |
| 523 | if isinstance(value, bytes): |
| 524 | # Already serialized |
| 525 | if value[0] == b"{" and self.use_header: |
| 526 | # Serialized, but doesn't contain header prefix, add it (assume migration from |
| 527 | # format without a header) |
| 528 | return "n:o:" + value |
| 529 | |
| 530 | return value |
| 531 | |
| 532 | if not isinstance(value, dict): |
| 533 | raise ValueError( |
| 534 | "value argument must be a dictionary (got: %s)" % type(value) |
| 535 | ) |
| 536 | |
| 537 | return self._serialize_field_value(value) |
| 538 | |
| 539 | def to_python(self, value): |
| 540 | if isinstance(value, dict): |
| 541 | # Old format which used a native dict with escaped special characters |
| 542 | # TODO: We can remove that once we assume there is no more old style data in the |
| 543 | # database and save quite some time. |
| 544 | value = mongoescape.unescape_chars(value) |
| 545 | return value |
| 546 | |
| 547 | if isinstance(value, bytes): |
| 548 | return self.parse_field_value(value) |
| 549 | |
| 550 | return value |
no outgoing calls