Interface API¶
general_manager.interface.base_interface.InterfaceBase ¶
Bases: ABC
Common base API for interfaces backing GeneralManager classes.
__init_subclass__ ¶
__init_subclass__(**kwargs)
Initialize capability-related class state for newly created subclasses.
This method resets per-subclass capability registries and configuration to a clean default, merges configured capability overrides into the class's capability_overrides mapping, and clears the flag that marks configured capabilities as applied. Any keyword arguments are forwarded to the superclass implementation.
__init__ ¶
__init__(*args, **kwargs)
Initialize the interface using the provided identification inputs.
Positional arguments are mapped to the interface's declared input fields by position; keyword arguments are matched by name. Inputs are validated and normalized according to the interface's input field definitions and the resulting normalized identification is stored on the instance as self.identification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args | Any | Positional identification values corresponding to the interface's input field order. | () |
**kwargs | Any | Named identification values matching the interface's input field names. | {} |
set_capability_selection classmethod ¶
set_capability_selection(selection)
Attach a resolved capability selection to the interface and update its active capability names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection | CapabilitySelection | The resolved capability selection whose | required |
get_capabilities classmethod ¶
get_capabilities()
Get the capability names attached to this interface class.
Returns:
| Type | Description |
|---|---|
frozenset[CapabilityName] | frozenset[CapabilityName]: A frozenset of capability names registered on the interface class. |
get_capability_handler classmethod ¶
get_capability_handler(name)
Retrieve the capability instance associated with the given capability name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | CapabilityName | The capability identifier to look up. | required |
Returns:
| Type | Description |
|---|---|
'Capability | None' | Capability | None: The capability handler registered for |
iter_capability_configs classmethod ¶
iter_capability_configs()
Iterate configured capability entries declared on the interface.
Returns:
| Type | Description |
|---|---|
Iterable[InterfaceCapabilityConfig] | Iterable[InterfaceCapabilityConfig]: An iterable of capability configuration entries registered on the interface. |
require_capability classmethod ¶
require_capability(name, *, expected_type=None)
Retrieve the configured capability handler for the interface by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | CapabilityName | The capability identifier to look up. | required |
expected_type | type[Capability] | None | If provided, require the returned handler to be an instance of this type. | None |
Returns:
| Name | Type | Description |
|---|---|---|
Capability | 'Capability' | The capability handler instance corresponding to |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the interface has no capability configured under |
TypeError | If |
capability_selection classmethod ¶
capability_selection()
Return the resolved capability selection associated with this interface.
@returns CapabilitySelection if a selection has been set, None otherwise.
parse_input_fields_to_identification ¶
parse_input_fields_to_identification(*args, **kwargs)
Convert positional and keyword inputs into a validated identification mapping for the interface's input fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args | Any | Positional arguments matched, in order, to the interface's defined input fields. | () |
**kwargs | Any | Keyword arguments supplying input values by name. | {} |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | dict[str, Any]: Mapping of input field names to their validated values. |
Raises:
| Type | Description |
|---|---|
UnexpectedInputArgumentsError | If extra keyword arguments are provided that do not match any input field (after allowing keys suffixed with "_id"). |
MissingInputArgumentsError | If one or more required input fields are not provided. |
CircularInputDependencyError | If input fields declare dependencies that form a cycle and cannot be resolved. |
InvalidInputTypeError | If a provided value does not match the declared type for an input. |
InvalidPossibleValuesTypeError | If an input's |
InvalidInputValueError | If a provided value is not in the allowed set defined by an input's |
format_identification staticmethod ¶
format_identification(identification)
Normalise identification data by replacing manager instances with their IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identification | dict[str, Any] | Raw identification mapping possibly containing manager instances. | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | dict[str, Any]: Identification mapping with nested managers replaced by their identifications. |
create classmethod ¶
create(*args, **kwargs)
Create a new managed record in the underlying data store using the interface's inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args | Any | Positional input values corresponding to the interface's defined input fields. | () |
**kwargs | Any | Input values provided by name; unexpected extra keywords will be rejected. | {} |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | The created record or a manager-specific representation of the newly created entity. |
update ¶
update(*args, **kwargs)
Update the underlying managed record.
Returns:
| Type | Description |
|---|---|
Any | The updated record or a manager-specific result. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If this interface does not provide an update capability. |
delete ¶
delete(*args, **kwargs)
Delete the underlying record managed by this interface.
Delegates the deletion to the interface's configured delete capability and executes the operation with observability hooks.
Returns:
| Type | Description |
|---|---|
Any | The result of the delete operation as returned by the delete capability. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the interface does not provide a delete capability. |
get_data ¶
get_data()
Get the materialized data for this manager.
Returns:
| Type | Description |
|---|---|
Any | The materialized data for this manager (implementation-defined). |
Raises:
| Type | Description |
|---|---|
NotImplementedError | if reading is not supported for this manager. |
get_attribute_types classmethod ¶
get_attribute_types()
Retrieve metadata describing each attribute exposed by the manager.
Returns:
| Type | Description |
|---|---|
dict[str, AttributeTypedDict] | dict[str, AttributeTypedDict]: Mapping from attribute name to its metadata (keys include |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the manager does not provide a read capability implementing |
get_attributes classmethod ¶
get_attributes()
Retrieve attribute values exposed by the interface.
Returns:
| Type | Description |
|---|---|
dict[str, Any] | dict[str, Any]: Mapping of attribute names to their current values. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the interface does not provide a read capability implementing |
get_graph_ql_properties classmethod ¶
get_graph_ql_properties()
Collect GraphQLProperty descriptors declared on the interface's parent manager class.
Returns:
| Type | Description |
|---|---|
dict[str, GraphQLProperty] | dict[str, GraphQLProperty]: Mapping from attribute name to the corresponding GraphQLProperty instance found on the parent manager class. Returns an empty dict if no parent class is set or none of its attributes are GraphQLProperty instances. |
filter classmethod ¶
filter(**kwargs)
Filter records using the provided lookup expressions and return a Bucket of matches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Lookup expressions mapping field lookups (e.g., "name__icontains") to values. | {} |
Returns:
| Type | Description |
|---|---|
Bucket[Any] | Bucket[Any]: Bucket containing records that match the lookup expressions. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the interface's query capability does not implement filtering. |
exclude classmethod ¶
exclude(**kwargs)
Obtain a Bucket of records excluding those that match the given lookup expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Lookup expressions accepted by the query capability (e.g., field=value, field__lookup=value). | {} |
Returns:
| Type | Description |
|---|---|
Bucket[Any] | Bucket[Any]: A Bucket containing records that do not match the provided lookup expressions. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the interface's query capability does not implement an |
all classmethod ¶
all()
Retrieve a Bucket containing all records for this interface.
Returns:
| Type | Description |
|---|---|
Bucket[Any] | Bucket[Any]: A Bucket containing every record accessible via this interface. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If the configured query capability does not implement |
handle_interface classmethod ¶
handle_interface()
Provide pre- and post-creation hooks for GeneralManager class construction derived from the interface's lifecycle capability.
Returns:
| Type | Description |
|---|---|
tuple[classPreCreationMethod, classPostCreationMethod] | tuple[classPreCreationMethod, classPostCreationMethod]: - pre-create callable accepting (name, attrs, interface, base_model_class=None) and returning (attrs, interface_class, related_class). - post-create callable accepting (new_class, interface_class, model) and returning None. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If no lifecycle capability is declared and the class does not override handle_interface. |
get_field_type classmethod ¶
get_field_type(field_name)
Resolve the declared Python type for the named input field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name | str | Name of the input field to look up. | required |
Returns:
| Name | Type | Description |
|---|---|---|
type | type | The Python type declared for the specified field. |
Raises:
| Type | Description |
|---|---|
KeyError | If no input field with the given name is defined. |
general_manager.interface.orm_interface.OrmInterfaceBase ¶
Bases: InterfaceBase, Generic[HistoryModelT]
Common initialization + metadata shared by ORM-backed interfaces.
__init__ ¶
__init__(*args, search_date=None, **kwargs)
Initialize the ORM-backed interface, set the primary key from identification, normalize the optional search date, and load the corresponding history model instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_date | datetime | None | Optional datetime used to select a historical record; if provided and timezone-naive, it will be converted to a timezone-aware datetime. | None |
normalize_search_date staticmethod ¶
normalize_search_date(search_date)
Ensure the provided search_date is timezone-aware.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_date | datetime | None | A datetime to normalize; may be naive or timezone-aware. | required |
Returns:
| Type | Description |
|---|---|
datetime | None | datetime | None: The input converted to a timezone-aware datetime if it was naive, the original datetime if already timezone-aware, or None if no date was provided. |
handle_custom_fields classmethod ¶
handle_custom_fields(model)
Retrieve custom-field metadata for the given model from the configured ORM lifecycle capability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[Model] | Model | Model class or model instance to describe. | required |
Returns:
| Type | Description |
|---|---|
tuple[list[str], list[str]] | tuple[list[str], list[str]]: A pair of lists of custom field names as returned by the lifecycle capability. |
general_manager.interface.interfaces.database.DatabaseInterface ¶
Bases: OrmInterfaceBase[GeneralManagerModel]
CRUD-capable interface backed by a dynamically generated Django model.
general_manager.interface.interfaces.existing_model.ExistingModelInterface ¶
Bases: OrmInterfaceBase[ExistingModelT]
Interface that reuses an existing Django model instead of generating a new one.
get_field_type classmethod ¶
get_field_type(field_name)
Retrieve the Python type for a named field on the wrapped Django model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name | str | Name of the field on the underlying Django model. | required |
Returns:
| Name | Type | Description |
|---|---|---|
type | type | The Python type corresponding to the specified model field. |
general_manager.interface.interfaces.read_only.ReadOnlyInterface ¶
Bases: OrmInterfaceBase[GeneralManagerBasisModel]
Interface that reads static JSON data into a managed read-only model.
general_manager.interface.interfaces.calculation.CalculationInterface ¶
Capabilities¶
general_manager.interface.capabilities.orm ¶
ORM-backed capability implementations.
HistoryNotSupportedError ¶
Bases: RuntimeError
Raised when historical lookups are requested but not supported.
OrmHistoryCapability dataclass ¶
Bases: BaseCapability
Lookup historical records for ORM-backed interfaces.
get_historical_record ¶
get_historical_record(
interface_cls, instance, search_date=None
)
Retrieve the model's historical record for the given instance as of the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The ORM interface class used to resolve capability-specific settings (for example, a database alias). | required |
instance | Any | The object that must implement SupportsHistory; if it does not, the function returns None. | required |
search_date | datetime | None | The cutoff date; the function returns the most recent historical record whose | None |
Returns:
| Type | Description |
|---|---|
Any | None | Any | None: The historical model instance that was current at |
get_historical_queryset ¶
get_historical_queryset(interface_cls, search_date)
Retrieve a queryset representing the historical state as of the given date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type['OrmInterfaceBase'] | ORM interface whose underlying model provides the historical manager. | required |
search_date | datetime | Cutoff datetime for historical snapshot lookup. | required |
Returns:
| Type | Description |
|---|---|
QuerySet | models.QuerySet: QuerySet representing the state at |
Raises:
| Type | Description |
|---|---|
HistoryNotSupportedError | If the model does not expose a history manager. |
get_historical_record_by_pk ¶
get_historical_record_by_pk(interface_cls, pk, search_date)
Retrieve the most recent historical record for the model identified by pk with a history date not later than search_date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type['OrmInterfaceBase'] | ORM interface whose underlying model provides the historical manager. | required |
pk | Any | Primary key of the target model record. | required |
search_date | datetime | None | Cutoff datetime; only history records with | required |
Returns:
| Type | Description |
|---|---|
Any | None | Any | None: The historical model instance with the latest |
OrmLifecycleCapability dataclass ¶
Bases: BaseCapability
Handle creation and configuration of ORM-backed interfaces.
pre_create ¶
pre_create(*, name, attrs, interface, base_model_class)
Prepare ORM model, concrete interface class, and factory before the parent class is created.
Creates a Django model class from fields discovered on the provided interface (applying any Meta configuration such as soft-delete and rules), finalizes its metadata, builds a concrete interface subclass bound to that model, and installs a Factory class and Interface class into the provided attrs mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The name to use for the generated model and factory. | required |
attrs | dict[str, Any] | The attribute dict for the class being created; will be updated with "Interface", "Factory", and "_interface_type". | required |
interface | type[OrmInterfaceBase] | The interface class that defines model fields and optional Meta/Factory configuration. | required |
base_model_class | type[GeneralManagerBasisModel] | Base model class to derive the generated model from (may be adjusted for soft-delete support). | required |
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], type['OrmInterfaceBase'], type[GeneralManagerBasisModel]] | tuple[dict[str, Any], type[OrmInterfaceBase], type[GeneralManagerBasisModel]]: - The possibly-modified attrs mapping. - The concrete interface subclass bound to the generated model. - The generated Django model class. |
post_create ¶
post_create(*, new_class, interface_class, model)
Attach the created interface class and model to each other and assign ORM managers to the new class.
This function links the generated interface and model to the newly created class by setting the interface's parent class and the model's general manager class. It also obtains and assigns the default manager to new_class.objects, and if soft-delete is enabled for the interface, assigns an all_objects manager that includes inactive/soft-deleted records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_class | type | The class that was just created for the interface (the concrete manager/interface class). | required |
interface_class | type[OrmInterfaceBase] | The concrete interface subclass bound to the model. | required |
model | type[GeneralManagerBasisModel] | None | The ORM model class created for the interface, or None if no model was generated. | required |
describe_custom_fields ¶
describe_custom_fields(model)
List Django Field names declared on the given model and generate ignore markers for each field's value and unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[Model] | Model | Model class or instance to inspect for attributes that are instances of Django | required |
Returns:
| Name | Type | Description |
|---|---|---|
field_names | list[str] | Names of discovered model fields (uses the field's |
ignore | list[str] | Generated ignore markers in the form |
OrmCreateCapability dataclass ¶
Bases: BaseCapability
Create new ORM instances using capability-driven configuration.
create ¶
create(interface_cls, *args, **kwargs)
Create a new ORM model instance from the provided payload and persist it with optional creator and history metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class that defines the target model and capabilities. | required |
*args | Any | Ignored positional arguments (kept for signature compatibility). | () |
**kwargs | Any | Field values used to construct the instance. Recognized special keys: creator_id (int, optional): Identifier to record as the creator/changed_by of the saved instance. history_comment (str, optional): Change reason to attach to the created instance's history. | {} |
Returns:
| Name | Type | Description |
|---|---|---|
result | dict[str, Any] | A dictionary containing the new instance primary key as {"id": |
OrmDeleteCapability dataclass ¶
Bases: BaseCapability
Delete (or deactivate) ORM instances.
delete ¶
delete(interface_instance, *args, **kwargs)
Delete or deactivate the provided ORM interface instance according to the interface's deletion policy.
If soft-delete is enabled for the interface, the instance is marked inactive (requires the instance to implement SupportsActivation) and saved with an optional history comment indicating deactivation. If soft-delete is not enabled, the instance is hard-deleted inside a database transaction using the support-provided database alias when available; the function attempts to set changed_by_id from creator_id and attaches the provided history comment as the change reason before deletion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_instance | 'OrmInterfaceBase' | The interface-wrapped model instance to remove. | required |
Returns:
| Name | Type | Description |
|---|---|---|
result | dict[str, Any] | A dict containing the primary key under the key |
Raises:
| Type | Description |
|---|---|
MissingActivationSupportError | If soft-delete is enabled but the instance does not implement activation support. |
OrmMutationCapability dataclass ¶
Bases: BaseCapability
Common utilities to modify ORM instances.
assign_simple_attributes ¶
assign_simple_attributes(interface_cls, instance, kwargs)
Apply simple (non-relational) attribute updates to a Django model instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance | Model | The model instance to modify. | required |
kwargs | dict[str, Any] | Mapping of field names to values; entries with the sentinel | required |
Returns:
| Type | Description |
|---|---|
Model | models.Model: The same instance after attribute assignment. |
Raises:
| Type | Description |
|---|---|
InvalidFieldValueError | If assigning a value raises a |
InvalidFieldTypeError | If assigning a value raises a |
save_with_history ¶
save_with_history(
interface_cls, instance, *, creator_id, history_comment
)
Persist the model instance while recording creator metadata and an optional change reason.
Performs the save inside an atomic transaction using the interface's configured database alias when available, sets changed_by_id on the instance if the attribute exists, runs model validation, and attaches a change reason after a successful save when history_comment is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The interface class used to resolve support capabilities and configuration. | required |
instance | Model | The Django model instance to validate and save. | required |
creator_id | int | None | Identifier of the user or process responsible for the change; assigned to | required |
history_comment | str | None | Optional comment describing the change; attached as a change reason after save when provided. | required |
Returns:
| Name | Type | Description |
|---|---|---|
int | int | The primary key ( |
apply_many_to_many ¶
apply_many_to_many(
interface_cls,
instance,
*,
many_to_many_kwargs,
history_comment
)
Apply many-to-many updates to a model instance's related fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class owning the model (used for observability). | required |
instance | Model | The model instance whose relationships will be updated. | required |
many_to_many_kwargs | dict[str, list[int]] | Mapping of relation keys to lists of related object IDs. Each key is expected to end with the suffix | required |
history_comment | str | None | Optional change reason to attach to the instance's history after updates. | required |
Returns:
| Type | Description |
|---|---|
Model | models.Model: The same model instance after its many-to-many relations have been updated. |
OrmUpdateCapability dataclass ¶
Bases: BaseCapability
Update existing ORM instances.
update ¶
update(interface_instance, *args, **kwargs)
Update the model instance referenced by the given interface instance with the provided payload, persisting changes and recording history and many-to-many updates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_instance | OrmInterfaceBase | Interface wrapper whose | required |
*args | Any | Ignored. | () |
**kwargs | Any | Field values to apply; may include | {} |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | dict[str, Any]: A mapping containing the saved instance id as {"id": |
OrmValidationCapability dataclass ¶
Bases: BaseCapability
Validate and normalize payloads used by mutation capabilities.
normalize_payload ¶
normalize_payload(interface_cls, *, payload)
Normalize and split a mutation payload into simple field values and many-to-many relation values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type | The interface class whose schema/normalizer should be used. | required |
payload | dict[str, Any] | Raw input payload to validate and normalize. | required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple | tuple[dict[str, Any], dict[str, list[Any]]] |
|
OrmPersistenceSupportCapability dataclass ¶
Bases: BaseCapability
Expose shared helpers to work with Django ORM models.
get_database_alias ¶
get_database_alias(interface_cls)
Retrieve the database alias declared on an ORM interface class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The ORM interface class to inspect for a | required |
Returns:
| Type | Description |
|---|---|
str | None | str | None: The value of the class attribute |
get_manager ¶
get_manager(interface_cls, *, only_active=True)
Obtain the Django manager for the interface's model, selecting between the active (soft-delete filtered) or all manager and honoring the interface's database alias.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class providing the Django model and optional metadata. | required |
only_active | bool | If True (default), return the active manager; if False, return the unfiltered/all manager. | True |
Returns:
| Type | Description |
|---|---|
Manager | django.db.models.Manager: The resolved manager for the interface's model. |
Notes
This function also caches the resolved active manager onto interface_cls._active_manager.
get_queryset ¶
get_queryset(interface_cls)
Retrieve an active queryset for the interface's model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The interface class whose underlying Django model will be queried. | required |
Returns:
| Type | Description |
|---|---|
QuerySet | models.QuerySet: A Django QuerySet containing the model's active records. |
get_payload_normalizer ¶
get_payload_normalizer(interface_cls)
Return a PayloadNormalizer configured for the interface's Django model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class providing the | required |
Returns:
| Name | Type | Description |
|---|---|---|
PayloadNormalizer | PayloadNormalizer | A normalizer instance bound to the interface's Django |
get_field_descriptors ¶
get_field_descriptors(interface_cls)
Get or build cached field descriptors for the given ORM interface class.
If descriptors are not already present on the interface class, this populates and caches them on the class as _field_descriptors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The ORM interface class to inspect. | required |
Returns:
| Type | Description |
|---|---|
dict[str, FieldDescriptor] | dict[str, FieldDescriptor]: Mapping of field names to their FieldDescriptor. |
resolve_many_to_many ¶
resolve_many_to_many(
interface_instance, field_call, field_name
)
Resolve a many-to-many relationship for an interface instance and return a queryset of the related target records, using historical snapshots when applicable.
If the relation's through/model is a HistoricalChanges subclass, the function: - Locates the corresponding related attribute on the historical model and collects related IDs. - If the target model has no history support or the interface instance has no search date, returns the live target model queryset filtered by those IDs. - If the target model supports history and a search date is present, returns the historical snapshot queryset as of that date filtered by those IDs. If the target field or related attribute cannot be resolved, an empty queryset for the appropriate model is returned. If the through/model is not historical, the original related manager's queryset is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_instance | OrmInterfaceBase | The interface wrapper containing the model instance and optional search date. | required |
field_call | str | Attribute name on the instance to access the related manager (e.g., the many-to-many manager accessor). | required |
field_name | str | Field name on the interface's model corresponding to the relation target. | required |
Returns:
| Type | Description |
|---|---|
QuerySet[Any] | models.QuerySet[Any]: A queryset of the related target records or their historical snapshots when applicable. |
OrmQueryCapability dataclass ¶
Bases: BaseCapability
Expose DatabaseBucket operations via the capability configuration.
filter ¶
filter(interface_cls, **kwargs)
Builds a DatabaseBucket representing a queryset filtered by the provided lookup kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class whose model and configuration determine queryset construction. | required |
**kwargs | Any | Lookup expressions passed through the payload normalizer; may include | {} |
Returns:
| Name | Type | Description |
|---|---|---|
DatabaseBucket | DatabaseBucket | A container holding the resulting Django queryset (cast to the model's queryset type), the interface's parent class, and the normalized filter kwargs. |
exclude ¶
exclude(interface_cls, **kwargs)
Builds a DatabaseBucket representing a queryset that excludes records matching the provided filter criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The ORM interface class whose model and metadata are used to construct the queryset. | required |
**kwargs | Any | Filter lookup expressions to apply as exclusion criteria. May include | {} |
Returns:
| Name | Type | Description |
|---|---|---|
DatabaseBucket | DatabaseBucket | A container holding the resulting Django queryset, the interface's parent class, and the normalized filter dictionary used for the exclusion. |
OrmReadCapability dataclass ¶
Bases: BaseCapability
Fetch ORM instances (or historical snapshots) for interface instances.
get_data ¶
get_data(interface_instance)
Retrieve the current model instance or a historical snapshot for the given ORM interface instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_instance | OrmInterfaceBase | Interface wrapper containing the primary key ( | required |
Returns:
| Type | Description |
|---|---|
Any | The live model instance or a historical record corresponding to |
Raises:
| Type | Description |
|---|---|
DoesNotExist | If no matching live instance or historical record exists. |
get_attribute_types ¶
get_attribute_types(interface_cls)
Return a mapping of field names to copies of their field descriptor metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The ORM interface class whose field descriptors will be queried. | required |
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]] | dict[str, dict[str, Any]]: A dict mapping each field name to a shallow copy of that field's |
get_attributes ¶
get_attributes(interface_cls)
Return a mapping of field names to their accessor callables for the given ORM interface class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The interface class whose model field descriptors will be used. | required |
Returns:
| Type | Description |
|---|---|
dict[str, Callable[[Any], Any]] | dict[str, Callable[[Any], Any]]: A dictionary mapping each field name to a callable that, given an instance, returns that field's value. |
get_field_type ¶
get_field_type(interface_cls, field_name)
Determine the effective type associated with a model field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | Interface class whose underlying Django model contains the field. | required |
field_name | str | Name of the field on the model. | required |
Returns:
| Name | Type | Description |
|---|---|---|
type | type | The class used to represent the field's values: the related model's |
SoftDeleteCapability ¶
Bases: BaseCapability
Track whether soft delete behavior should be applied.
__init__ ¶
__init__(enabled=False)
Initialize the soft-delete capability with a default enabled state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled | bool | Initial enabled state for soft-delete; True to enable, False to disable. | False |
setup ¶
setup(interface_cls)
Initialize the capability's soft-delete state for the given interface class.
Determines the default enabled state in this order: 1) use interface_cls._soft_delete_default if present; 2) else use interface_cls._model._meta.use_soft_delete if available; 3) otherwise fall back to the capability's current enabled value. Sets self.enabled to the resulting boolean and then calls the base setup with the same interface class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[InterfaceBase] | The interface class being configured. | required |
is_enabled ¶
is_enabled()
Indicates whether soft-delete behavior is enabled for this capability.
Returns:
| Name | Type | Description |
|---|---|---|
bool | bool | True if soft-delete is enabled, False otherwise. |
set_state ¶
set_state(enabled)
Set whether soft-delete is enabled for this capability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled | bool | True to enable soft-delete behavior, False to disable it. | required |
get_support_capability ¶
get_support_capability(interface_cls)
Resolve and return the "orm_support" capability instance for the given interface class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type | The ORM interface class to query for the capability. | required |
Returns:
| Name | Type | Description |
|---|---|---|
OrmPersistenceSupportCapability | OrmPersistenceSupportCapability | The resolved persistence support capability instance. |
is_soft_delete_enabled ¶
is_soft_delete_enabled(interface_cls)
Determine whether soft-delete behavior is enabled for the given interface class.
Checks the interface's soft_delete capability first, then the model's _meta.use_soft_delete, and finally the interface's _soft_delete_default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase] | The interface class to evaluate. | required |
Returns:
| Name | Type | Description |
|---|---|---|
bool | bool |
|
general_manager.interface.capabilities.read_only.management ¶
Capabilities that power ReadOnlyInterface behavior.
ReadOnlyManagementCapability dataclass ¶
Bases: BaseCapability
Provide schema verification and data-sync behavior for read-only interfaces.
get_startup_hook_dependency_resolver ¶
get_startup_hook_dependency_resolver(interface_cls)
Return a resolver function that identifies read-only interfaces which must run before a given interface's startup hook.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase[Any]] | The interface class for which to obtain a startup-hook dependency resolver. | required |
Returns:
| Type | Description |
|---|---|
Callable[[type[object]], set[type[object]]] | Callable[[type[object]], Set[type[object]]]: A callable that, when invoked with an interface class, returns a set of read-only interface classes that should be executed prior to that interface's startup hook. |
get_unique_fields ¶
get_unique_fields(model)
Gather candidate unique field names declared on the Django model, remapping measurement-backed fields to their public attribute names.
Includes fields marked unique=True, fields listed in unique_together (or equivalent tuple/list/set entries), and fields referenced by UniqueConstraint definitions. Excludes the primary key named "id". If the model has no _meta, returns an empty set.
Returns:
| Type | Description |
|---|---|
set[str] | set[str]: A set of unique field names (with MeasurementField-backed value attributes remapped to their wrapper attribute names). |
ensure_schema_is_up_to_date ¶
ensure_schema_is_up_to_date(
interface_cls, manager_cls, model, *, connection=None
)
Verify that the Django model's declared schema matches the actual database table and return any schema-related warnings.
Performs the following checks and returns corresponding Django Warning objects when applicable: - Model metadata (_meta) is missing. - db_table is not defined on the model meta. - The named database table does not exist. - The table's columns differ from the model's local field columns (missing or extra columns).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection | optional | Database connection to use for introspection. If omitted, the default Django connection is used. | None |
Returns:
| Type | Description |
|---|---|
list[Warning] | list[Warning]: A list of Django system-check |
sync_data ¶
sync_data(
interface_cls,
*,
connection=None,
transaction=None,
integrity_error=None,
json_module=None,
logger_instance=None,
unique_fields=None,
schema_validated=False
)
Synchronize the interface's bound read-only JSON data into the underlying Django model, creating, updating, and deactivating records to match the input.
Parses the read-only payload defined on the interface's parent class, enforces a set of unique identifying fields to match incoming items to existing rows, writes only model-editable fields, marks matched records active, creates missing records, and deactivates previously active records not present in the incoming data. If schema validation is enabled (or performed), aborts when schema warnings are detected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase[Any]] | Read-only interface class whose parent class must expose | required |
connection | Optional[Any] | Optional Django DB connection to use instead of the default. | None |
transaction | Optional[Any] | Optional Django transaction management module or object to use instead of the default. | None |
integrity_error | Optional[Any] | Optional exception class to treat as a DB integrity error (defaults to Django's IntegrityError). | None |
json_module | Optional[Any] | Optional JSON-like module to parse JSON strings (defaults to the standard library json). | None |
logger_instance | Optional[Any] | Optional logger to record sync results; falls back to the capability's resolved logger. | None |
unique_fields | set[str] | None | Explicit set of field names to use as the unique identifier for items; when omitted, the model's unique metadata is used. | None |
schema_validated | bool | When True, skip runtime schema validation; when False, ensure_schema_is_up_to_date is called before syncing and the sync is aborted if warnings are returned. | False |
get_startup_hooks ¶
get_startup_hooks(interface_cls)
Provide a startup hook that triggers read-only data synchronization for the given interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase[Any]] | Interface class used to derive the bound manager and model. | required |
Returns:
| Type | Description |
|---|---|
Callable[[], None] | tuple[Callable[[], None], ...]: A one-element tuple containing a callable that runs synchronization when invoked, |
... | or an empty tuple if the interface lacks the necessary manager/model metadata. The callable invokes the capability's |
tuple[Callable[[], None], ...] | sync logic and silently skips if the read-only binding is not yet available. |
get_system_checks ¶
get_system_checks(interface_cls)
Provide a system check function that validates the read-only model schema against the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[OrmInterfaceBase[Any]] | The read-only interface class whose binding (parent manager and model) will be inspected. | required |
Returns:
| Type | Description |
|---|---|
tuple[Callable[[], list[Warning]], ...] | tuple[Callable[[], list[Warning]], ...]: A tuple containing a single callable. When invoked, the callable returns a list of |
general_manager.interface.capabilities.calculation.lifecycle ¶
Capabilities tailored for calculation interfaces.
CalculationReadCapability dataclass ¶
Bases: BaseCapability
Calculations expose inputs only and never persist data.
get_data ¶
get_data(interface_instance)
Indicates that calculation interfaces do not persist instance data and this operation is unsupported.
Raises:
| Type | Description |
|---|---|
NotImplementedError | Always raised with the message "Calculations do not store data." |
get_attribute_types ¶
get_attribute_types(interface_cls)
Builds a mapping of input field metadata for a calculation interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type | CalculationInterface subclass whose | required |
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]] | dict[str, dict[str, Any]]: A dictionary where each key is an input field name and each value is a metadata dictionary with: - "type": the field's declared Python type, - "default": None, - "is_editable": False, - "is_required": whether the field is required ( |
get_attributes ¶
get_attributes(interface_cls)
Provide attribute accessors for each input field of the calculation interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[CalculationInterface] | Calculation interface class whose | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | dict[str, Callable[[Any], Any]]: Mapping from each input field name to a callable. Each callable takes an interface instance ( |
get_field_type ¶
get_field_type(interface_cls, field_name)
Retrieve the declared Python type for a named input field on the calculation interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[CalculationInterface] | Calculation interface class containing | required |
field_name | str | Name of the input field to look up. | required |
Returns:
| Name | Type | Description |
|---|---|---|
type | type | The Python type declared for the input field. |
Raises:
| Type | Description |
|---|---|
KeyError | If |
CalculationQueryCapability dataclass ¶
Bases: BaseCapability
Expose CalculationBucket helpers via the generic query capability.
filter ¶
filter(interface_cls, **kwargs)
Create a filtered CalculationBucket for the given calculation interface using the provided query criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[CalculationInterface] | Calculation interface whose underlying parent class will be queried. | required |
**kwargs | Any | Query filter parameters forwarded to CalculationBucket.filter. | {} |
Returns:
| Name | Type | Description |
|---|---|---|
CalculationBucket | CalculationBucket | A bucket representing the filtered set of calculations. |
exclude ¶
exclude(interface_cls, **kwargs)
Execute an exclusion query against the calculation interface's bucket and record the operation for observability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[CalculationInterface] | The calculation interface class whose parent model is used to construct the CalculationBucket. | required |
**kwargs | Any | Filter criteria forwarded to the bucket's | {} |
Returns:
| Name | Type | Description |
|---|---|---|
CalculationBucket | CalculationBucket | A bucket representing the query with the specified exclusions applied. |
all ¶
all(interface_cls)
Retrieve all calculation instances for the specified calculation interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[CalculationInterface] | The calculation interface class whose calculations should be returned. | required |
Returns:
| Name | Type | Description |
|---|---|---|
CalculationBucket | CalculationBucket | A bucket containing all calculation instances for the given interface. |
CalculationLifecycleCapability dataclass ¶
Bases: BaseCapability
Manage calculation interface pre/post creation hooks.
pre_create ¶
pre_create(*, name, attrs, interface)
Builds and attaches a specialized CalculationInterface subclass and updates class attributes for creation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The declared name for the new interface class. | required |
attrs | dict[str, Any] | The attribute mapping that will be updated with interface metadata; this function sets "_interface_type" and "Interface". | required |
interface | type[CalculationInterface] | The base calculation interface class used to collect Input-declared fields. | required |
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], type['CalculationInterface'], None] | tuple[dict[str, Any], type[CalculationInterface], None]: A tuple containing the possibly modified |
post_create ¶
post_create(*, new_class, interface_class, model=None)
Attach the created class as the parent implementation for a calculation interface.
Sets the interface_class's _parent_class attribute to new_class and records the operation for observability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_class | type | The concrete class just created for the interface. | required |
interface_class | type[CalculationInterface] | The interface class whose parent link will be updated. | required |
model | None | Reserved for compatibility with lifecycle hooks; not used. | None |
general_manager.interface.capabilities.existing_model.resolution ¶
Capabilities specialized for ExistingModelInterface.
ExistingModelResolutionCapability dataclass ¶
Bases: BaseCapability
Resolve and configure the Django model used by ExistingModelInterface.
resolve_model ¶
resolve_model(interface_cls)
Resolve and bind the Django model referenced by an ExistingModelInterface subclass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[ExistingModelInterface] | The interface class whose | required |
Returns:
| Type | Description |
|---|---|
type[Model] | type[models.Model]: The resolved Django model class. |
Raises:
| Type | Description |
|---|---|
MissingModelConfigurationError | If the interface has no |
InvalidModelReferenceError | If the |
ensure_history ¶
ensure_history(model, interface_cls=None)
Register simple history tracking for the given Django model if it is not already registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[Model] | The Django model class to enable history tracking on. | required |
interface_cls | type['ExistingModelInterface'] | None | Optional interface class associated with the model; when provided, the registration is attributed to that interface. | None |
apply_rules ¶
apply_rules(interface_cls, model)
Apply the interface's Meta.rules to the Django model and wire a compatible full_clean method.
If the interface defines a Meta.rules sequence, this function appends those rules to any existing rules on model._meta and assigns the combined list back to model._meta.rules. It then replaces model.full_clean with a full-clean helper appropriate for the model. If no rules are defined on the interface, the model is left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface_cls | type[ExistingModelInterface] | The interface class whose Meta.rules will be applied. | required |
model | type[Model] | The Django model to receive combined rules and a patched full_clean. | required |
pre_create ¶
pre_create(*, name, attrs, interface)
Prepare and return attributes and types needed to create a concrete interface class tied to an existing Django model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The name to use for the generated concrete interface and its factory. | required |
attrs | dict[str, Any] | Attribute mapping for the class being created; this mapping will be updated with keys such as "_interface_type", "Interface", and "Factory". | required |
interface | type[ExistingModelInterface] | The ExistingModelInterface subclass that defines the model reference and optional Factory to base the concrete interface on. | required |
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], type['ExistingModelInterface'], type[Model]] | tuple[dict[str, Any], type[ExistingModelInterface], type[models.Model]]: A tuple containing the (possibly mutated) attrs dict to use when creating the class, the generated concrete interface type (with its model wired), and the resolved Django model class. |
post_create ¶
post_create(*, new_class, interface_class, model)
Finalize wiring between the newly created concrete class, its interface, and the Django model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_class | type | The newly created concrete manager/class that will be attached to the interface and model. | required |
interface_class | type[ExistingModelInterface] | The interface class from which the concrete class was created. | required |
model | type[Model] | None | The resolved Django model associated with the interface, or | required |
Description
If a model is provided, attaches new_class as the interface's _parent_class and the model's _general_manager_class, assigns new_class.objects using the ORM persistence capability for the interface, and if soft-delete support is enabled, ensures the model exposes all_objects (falling back to _default_manager if missing) and assigns new_class.all_objects to a manager that returns both active and inactive records.
build_factory ¶
build_factory(
*, name, interface_cls, model, factory_definition=None
)
Create a concrete AutoFactory subclass configured for the given interface and Django model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Base name used to derive the generated factory class name (result will be "{name}Factory"). | required |
interface_cls | type[ExistingModelInterface] | The interface type the factory will produce instances for. | required |
model | type[Model] | The Django model that the factory's Meta.model should reference. | required |
factory_definition | type | None | Optional prototype class whose public attributes are copied into the generated factory. | None |
Returns:
| Type | Description |
|---|---|
type[AutoFactory] | type[AutoFactory]: A newly created AutoFactory subclass named "{name}Factory" with its |