JSON field. This field can store dictionaries or lists of any JSON-compliant structure. You can use generics to make static checking more friendly. Example: ``JSONField[dict[str, str]]`` You can specify your own custom JSON encoder/decoder, leaving at the default should work well
| 709 | |
| 710 | |
| 711 | class JSONField(Field[T], dict, list): # type: ignore |
| 712 | """ |
| 713 | JSON field. |
| 714 | |
| 715 | This field can store dictionaries or lists of any JSON-compliant structure. |
| 716 | |
| 717 | You can use generics to make static checking more friendly. Example: ``JSONField[dict[str, str]]`` |
| 718 | |
| 719 | You can specify your own custom JSON encoder/decoder, leaving at the default should work well. |
| 720 | If you have ``orjson`` installed, we default to using that, |
| 721 | else the default ``json`` module will be used. |
| 722 | |
| 723 | ``encoder``: |
| 724 | The custom JSON encoder. |
| 725 | ``decoder``: |
| 726 | The custom JSON decoder. |
| 727 | |
| 728 | If you want to use Pydantic model as the field type for generating a better OpenAPI documentation, you can use ``field_type`` to specify the type of the field. |
| 729 | |
| 730 | ``field_type``: |
| 731 | The Pydantic model class. |
| 732 | |
| 733 | """ |
| 734 | |
| 735 | SQL_TYPE = "JSON" |
| 736 | indexable = False |
| 737 | |
| 738 | class _db_postgres: |
| 739 | SQL_TYPE = "JSONB" |
| 740 | |
| 741 | class _db_mssql: |
| 742 | SQL_TYPE = "NVARCHAR(MAX)" |
| 743 | |
| 744 | class _db_oracle: |
| 745 | SQL_TYPE = "NCLOB" |
| 746 | |
| 747 | def __init__( |
| 748 | self, |
| 749 | encoder: JsonDumpsFunc = JSON_DUMPS, |
| 750 | decoder: JsonLoadsFunc = JSON_LOADS, |
| 751 | **kwargs: Any, |
| 752 | ) -> None: |
| 753 | super().__init__(**kwargs) |
| 754 | self.encoder = encoder |
| 755 | self.decoder = decoder |
| 756 | if field_type := kwargs.get("field_type"): |
| 757 | self.field_type = field_type |
| 758 | |
| 759 | def to_db_value( |
| 760 | self, |
| 761 | value: T | dict | list | str | bytes | None, |
| 762 | instance: type[Model] | Model, |
| 763 | ) -> str | None: |
| 764 | self.validate(value) |
| 765 | if value is None: |
| 766 | return None |
| 767 | |
| 768 | if isinstance(value, (str, bytes)): |
no outgoing calls
searching dependent graphs…