diff --git a/xmodel/converters.py b/xmodel/converters.py index 137dff7..77e867b 100644 --- a/xmodel/converters.py +++ b/xmodel/converters.py @@ -1,4 +1,4 @@ -import uuid +from uuid import UUID import ciso8601 @@ -249,6 +249,33 @@ def convert_decimal( return Decimal(value) +def convert_uuid( + api, + direction: Direction, + field: Field, + value: Any, +): + if value is None or value is Null: + return value + + if direction is Direction.to_json: + # Convert UUID object into a str. + return str(value) + + if direction not in (Direction.to_model, Direction.from_json): + # We don't know the direction (new direct?) + raise XModelError( + f"Unknown direction ({direction}), can't convert value ({value}); " + f"is this a new direction I need to handle?" + ) + + # Going into model, return a UUID. + if isinstance(value, UUID): + return value + + return UUID(value) + + DEFAULT_CONVERTERS: Dict[Type, Converter] = { Decimal: convert_decimal, dt.date: convert_json_date, @@ -257,5 +284,5 @@ def convert_decimal( float: ConvertBasicType(basic_type=float), str: ConvertBasicType(basic_type=str), bool: ConvertBasicBool(), - uuid.UUID: ConvertBasicType(basic_type=str), + UUID: convert_uuid, } diff --git a/xmodel/remote/api.py b/xmodel/remote/api.py index ac9e491..88c6da8 100644 --- a/xmodel/remote/api.py +++ b/xmodel/remote/api.py @@ -1,5 +1,5 @@ import dataclasses -import uuid +from uuid import UUID from decimal import Decimal from logging import getLogger from typing import ( @@ -147,10 +147,10 @@ def response_state(self) -> ResponseState[M]: def get_via_id( self, id: Union[ - Union[int, str], - List[Union[int, str]], - Dict[str, Union[str, int]], - List[Dict[str, Union[str, int]]], + int | str | UUID, + List[int | str | UUID], + Dict[str, str | int | UUID], + List[Dict[str, str | int | UUID]], ], fields: FieldNames = Default, id_field: str = None, @@ -243,7 +243,7 @@ def get_via_id( value_type = type(id) # Treat a Decimal as a string for the purposes of querying for it. - if type(id) in (Decimal, uuid.UUID): + if type(id) in (Decimal, UUID): id = str(id) value_type = str