ModelRfield
Resource field for storing Pydantic BaseModelDTO objects.
ModelRfield provides automatic serialization and deserialization of Pydantic models (BaseModelDTO) to and from JSON. This ensures type-safe, validated storage of structured data objects with all the benefits of Pydantic.
The field automatically: - Serializes model instances to JSON strings using Pydantic - Deserializes JSON strings back to model instances - Validates data according to Pydantic model schema - Provides type hints and IDE support - Handles nested models and complex types
This is useful for: - Storing structured configuration objects - Complex data models with validation - API response objects - Typed data structures - Objects with nested relationships
Storage behavior: - Stored in KV_STORE by default - Not included in dict views by default (can be changed) - Automatically serialized to JSON on save - Automatically deserialized and validated on load
Example: ```python from gws_core.core.model.model_dto import BaseModelDTO from pydantic import Field
class UserConfig(BaseModelDTO):
name: str
age: int = Field(ge=0)
email: str
class MyResource(Resource):
# Store a user configuration object
user_config = ModelRfield(object_type=UserConfig)
# Included in dict view
summary = ModelRfield(object_type=SummaryDTO, include_in_dict_view=True)
# Usage
resource = MyResource()
resource.user_config = UserConfig(name='John', age=30, email='john@example.com')
# Validation happens automatically via Pydantic
```
Note: - The object_type must be a subclass of BaseModelDTO - Pydantic validation is applied during deserialization - Models can have complex nested structures - Default value is None (model is not instantiated by default)
include_in_dict_view: boolobject_type: typestorage: RFieldStorageInitialize a ModelRfield for storing Pydantic model objects.
typebool - FalseDeserialize a JSON string into a Pydantic model instance.
This method is called when loading the field from storage. It uses Pydantic's from_json_str method to deserialize and validate the data.
AnyBaseModelDTOGet the default value for this field.
If the default value is a Type or Callable, it will be called to generate a new default value. Otherwise, the default value is returned directly.
This ensures that mutable defaults (like lists or dicts) are not shared between Resource instances.
AnySerialize a Pydantic model instance to a JSON string.
This method is called when saving the field to storage. It uses Pydantic's to_json_str method to serialize the model.
BaseModelDTOAny