diff --git a/django_setup_configuration/documentation/model_directive.py b/django_setup_configuration/documentation/model_directive.py index 9805c18..b3dd7c0 100644 --- a/django_setup_configuration/documentation/model_directive.py +++ b/django_setup_configuration/documentation/model_directive.py @@ -20,6 +20,15 @@ class PolymorphicExample: commented_out_examples: list[Any] +def get_default_from_field_info(field_info: FieldInfo) -> Any: + if field_info.default != PydanticUndefined and field_info.default: + if isinstance(field_info.default, Enum): + return field_info.default.value + return field_info.default + elif field_info.default_factory and (default := field_info.default_factory()): + return default + + def yaml_set_comment_with_max_length( commented_map: CommentedMap, key: str, @@ -66,15 +75,9 @@ def insert_example_with_comments( yaml_set_comment_with_max_length( example_data, field_name, field_info.description, 80, indent=depth * 2 ) - if field_info.default != PydanticUndefined: - example_data.yaml_set_comment_before_after_key( - field_name, f"default value: {field_info.default}", indent=depth * 2 - ) - elif field_info.default_factory: + if default := get_default_from_field_info(field_info): example_data.yaml_set_comment_before_after_key( - field_name, - f"default value: {field_info.default_factory()}", - indent=depth * 2, + field_name, f"default value: {default}", indent=depth * 2 ) example_data.yaml_set_comment_before_after_key( field_name, f"required: {field_info.is_required()}", indent=depth * 2 @@ -137,6 +140,10 @@ def process_field_type( """ Processes a field type and generates example data based on its type. """ + # Handle basic types + if example := generate_basic_example(field_type, field_info): + return example + # Step 1: Handle Annotated if get_origin(field_type) == Annotated: # Extract the first argument from Annotated, which could be a Union @@ -168,22 +175,15 @@ def process_field_type( list_type = get_args(field_type)[0] return [process_field_type(list_type, field_info, field_name, depth + 1)] - # Handle basic types - return generate_basic_example(field_type, field_info) - -def generate_basic_example(field_type: Any, field_info) -> Any: +def generate_basic_example(field_type: Any, field_info: FieldInfo) -> Any: """ Generates a basic example for simple types like str, int, bool, etc. """ if field_info.examples: return field_info.examples[0] - elif field_info.default != PydanticUndefined and field_info.default: - if isinstance(field_info.default, Enum): - return field_info.default.value - return field_info.default - elif field_info.default_factory: - return field_info.default_factory() + elif default := get_default_from_field_info(field_info): + return default elif field_type == str: return "example_string" elif field_type == int: