Skip to content

Core modules and concepts

Core modules and concepts

This page summarizes the core building blocks in src/pydantic2django/core/, what they do, and the most important classes and methods to be aware of.

For full, up-to-date API details, see the API Reference generated by mkdocstrings: API Reference.

base_generator.py

  • purpose: Shared orchestration for generating static Django models.py from source models.
  • key class: BaseStaticGenerator[SourceModelType, FieldInfoType]
  • generate(): Top-level entrypoint; writes the rendered models file.
  • generate_models_file(): Orchestrates discovery, field/model setup, import dedupe, and template rendering.
  • discover_models(): Uses a BaseDiscovery to find candidate models and analyze dependencies.
  • setup_django_model(source_model): Runs the configured BaseModelFactory to populate a ConversionCarrier.
  • generate_model_definition(carrier): Renders a single model using model_definition.py.j2.
  • Abstract hooks to implement in concrete generators:
    • _get_source_model_name(carrier), _add_source_model_import(carrier), _prepare_template_context(defs, names, imports), _get_models_in_processing_order(), _get_model_definition_extra_context(carrier).
  • templates: Uses Jinja2 with templates under django/templates/.

discovery.py

  • purpose: Pluggable model discovery for different source types.
  • key class: BaseDiscovery[TModel]
  • discover_models(packages, app_label, user_filters): Scans packages/modules, applies built-in and user filters.
  • analyze_dependencies(): Build dependency graph (abstract).
  • get_models_in_registration_order(): Topological order (abstract).
  • Protected hooks: _is_target_model(obj), _default_eligibility_filter(model), _post_discovery_hook(), _resolve_forward_refs().

factories.py

  • purpose: Convert a source model and its fields into an in-memory Django model representation.
  • data objects:
  • ConversionCarrier[SourceModelType]: Conversion state (django fields, relationships, context, Meta, etc.).
  • FieldConversionResult: Result of converting a single field, including kwargs and imports.
  • base classes:
  • BaseFieldFactory[SourceFieldType]: create_field(field_info, model_name, carrier) (abstract).
  • BaseModelFactory[SourceModelType, SourceFieldType]: Implements orchestration via make_django_model(carrier) and common helpers:
    • _process_source_fields(carrier) (abstract)
    • _handle_field_collisions(carrier)
    • _create_django_meta(carrier)
    • _assemble_django_model_class(carrier)
    • _build_model_context(carrier) (abstract)

bidirectional_mapper.py

  • purpose: Central, bidirectional mapping between Python/Pydantic types and Django Fields.
  • key class: BidirectionalTypeMapper
  • get_django_mapping(python_type, field_info, parent_pydantic_model=None)(FieldType, kwargs)
  • get_pydantic_mapping(django_field)(python_type, field_info_kwargs)
  • Internals: _find_unit_for_pydantic_type, _find_unit_for_django_field, registry of TypeMappingUnit implementations.
  • exceptions: MappingError for invalid/unsupported cases.

mapping_units.py

  • purpose: Concrete TypeMappingUnit classes that implement mapping rules.
  • base class: TypeMappingUnit
  • matches(py_type, field_info) scoring; pydantic_to_django_kwargs(...); django_to_pydantic_field_info_kwargs(dj_field).
  • notable units: primitives (IntFieldMapping, StrFieldMapping, TextFieldMapping, BoolFieldMapping, FloatFieldMapping), numerics (DecimalFieldMapping), dates (DateFieldMapping, DateTimeFieldMapping, TimeFieldMapping, DurationFieldMapping), identifiers (UUIDFieldMapping), network/paths (EmailFieldMapping, URLFieldMapping, IPAddressFieldMapping, FilePathFieldMapping), files (FileFieldMapping, ImageFieldMapping), JSON (JsonFieldMapping), enums/choices (EnumFieldMapping), relationships (ForeignKeyMapping, OneToOneFieldMapping, ManyToManyFieldMapping), and the conceptual GenericForeignKeyMappingUnit.

typing.py

  • purpose: Type processing utilities for introspection and code generation.
  • key class: TypeHandler
  • process_field_type(field_type): Normalize Optional/List/Union/Annotated; produce simplified type object and metadata.
  • get_required_imports(type_obj): Compute import map for a type (including nested generics).
  • format_type_string(type_obj): Render a readable type string for generated code.
  • get_class_name(type_obj): Extract a canonical type name.
  • Logging helper: configure_core_typing_logging(...).

imports.py

  • purpose: Collect, categorize, and de-duplicate imports used in generated code.
  • key class: ImportHandler
  • add_import(module, name), add_pydantic_model_import(model_class), add_context_field_type_import(field_type)
  • deduplicate_imports(): Merge and flatten import statements for output.
  • Helpers for nested/generic types and cleaning generic names.

relationships.py

  • purpose: Track and resolve mappings between source models and generated Django models.
  • key classes:
  • RelationshipMapper: Holds a single mapping between a source model and a Django model.
  • RelationshipConversionAccessor: Registry and lookup utilities:
    • map_relationship(source_model, django_model), is_source_model_known(model)
    • get_django_model_for_pydantic(pydantic_model), get_pydantic_model_for_django(django_model)
    • get_django_model_for_dataclass(dataclass_model), available_source_models, available_django_models

context.py

  • purpose: Context storage and codegen for data that cannot be represented as first-class Django fields.
  • key classes:
  • FieldContext: Per-field context metadata and value.
  • ModelContext[SourceModelType]: Collection of context fields for a model; import synthesis; serialization helpers.
    • Methods: add_field(...), validate_context(...), get_required_imports(), to_conversion_dict().
  • ContextClassGenerator: Renders a context dataclass using the context_class.py.j2 template.

serialization.py

  • purpose: Safe value serialization utilities.
  • API: SerializationMethod enum, get_serialization_method(obj), serialize_value(value), is_serializable(obj).

defs.py

  • purpose: Shared type helpers and mapping definition structure.
  • API: is_serializable_type(field_type), is_pydantic_model(obj), TypeMappingDefinition.

filter_helpers.py

  • purpose: Small helpers to build discovery filters.
  • API: exclude_models([...]), include_models([...]), has_field(name), always_include(...).

utils/

  • strings.py: sanitize_string(value) for safe codegen strings; balanced(s) for quick bracket balance checks.
  • relationships.py: get_relationship_metadata(field_type) and type aliases for relationship detection.

See also the detailed API pages for these modules under the site’s API section: API Reference.