Skip to content

Measurement API

general_manager.measurement.measurement.Measurement

quantity property

quantity

Access the underlying pint quantity for advanced operations.

Returns:

Name Type Description
PlainQuantity PlainQuantity

Pint quantity representing the measurement value and unit.

magnitude property

magnitude

Fetch the numeric component of the measurement.

Returns:

Name Type Description
Decimal Decimal

Magnitude of the measurement in its current unit.

unit property

unit

Retrieve the unit label associated with the measurement.

Returns:

Name Type Description
str str

Canonical unit string as provided by the unit registry.

__init__

__init__(value, unit)

Create a Measurement from a numeric value and a unit label.

Converts the provided numeric-like value to a Decimal and constructs the internal quantity using the given unit.

Parameters:

Name Type Description Default
value Decimal | float | int | str

Numeric value to use as the measurement magnitude; strings and numeric types are coerced to Decimal.

required
unit str

Unit label registered in the module's unit registry (currency codes or physical unit names).

required

Raises:

Type Description
InvalidMeasurementInitializationError

If value cannot be converted to a Decimal.

__getstate__

__getstate__()

Produce a serialisable representation of the measurement.

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping with magnitude and unit entries for pickling.

__setstate__

__setstate__(state)

Recreate the internal quantity from a serialized representation.

Parameters:

Name Type Description Default
state dict[str, str]

Serialized state containing magnitude and unit values.

required

Returns:

Type Description
None

None

from_string classmethod

from_string(value)

Parse a textual representation into a Measurement.

Parameters:

Name Type Description Default
value str

A string in the form " " or a single numeric token for a dimensionless value.

required

Returns:

Name Type Description
Measurement Measurement

Measurement constructed from the parsed magnitude and unit.

Raises:

Type Description
InvalidDimensionlessValueError

If a single-token input cannot be parsed as a number.

InvalidMeasurementStringError

If the string does not contain a valid numeric magnitude followed by a parseable unit expression.

InvalidMeasurementInitializationError

If constructing the Measurement from the parsed parts fails.

format_decimal staticmethod

format_decimal(value)

Normalise decimals so integers have no fractional component.

Parameters:

Name Type Description Default
value Decimal

Decimal value that should be normalised.

required

Returns:

Name Type Description
Decimal Decimal

Normalised decimal with insignificant trailing zeros removed.

to

to(target_unit, exchange_rate=None)

Convert this measurement to the specified target unit, handling currency conversions when applicable.

Parameters:

Name Type Description Default
target_unit str

Unit label or currency code to convert the measurement into.

required
exchange_rate float | None

Exchange rate to use when converting between different currencies; ignored for same-currency conversions and physical-unit conversions.

None

Returns:

Name Type Description
Measurement Measurement

The measurement expressed in the target unit.

Raises:

Type Description
MissingExchangeRateError

If converting between two different currencies without providing an exchange rate.

is_currency

is_currency()

Determine whether the measurement's unit represents a configured currency.

Returns:

Name Type Description
bool bool

True if the unit matches one of the registered currency codes.

__add__

__add__(other)

Return the sum of this Measurement and another Measurement while enforcing currency and dimensional rules.

If both operands are currency units their currency codes must match. If both are physical units their dimensionalities must match. Mixing currency and physical units is not permitted.

Parameters:

Name Type Description Default
other Measurement

The addend measurement.

required

Returns:

Name Type Description
Measurement Measurement

A new Measurement representing the sum.

Raises:

Type Description
MeasurementOperandTypeError

If other is not a Measurement.

CurrencyMismatchError

If both operands are currencies with different currency codes.

IncompatibleUnitsError

If both operands are physical units but have different dimensionalities or the result cannot be represented as a pint.Quantity.

MixedUnitOperationError

If one operand is a currency and the other is a physical unit.

__sub__

__sub__(other)

Subtract another Measurement from this one, enforcing currency and unit compatibility.

Performs subtraction for two currency Measurements only when they share the same currency code, or for two physical Measurements only when they have the same dimensionality; mixing currency and physical units is disallowed.

Parameters:

Name Type Description Default
other Measurement

The measurement to subtract from this measurement.

required

Returns:

Name Type Description
Measurement Measurement

A new Measurement representing the difference.

Raises:

Type Description
MeasurementOperandTypeError

If other is not a Measurement.

CurrencyMismatchError

If both operands are currencies but use different currency codes.

IncompatibleUnitsError

If both operands are physical units but have incompatible dimensionality.

MixedUnitOperationError

If one operand is a currency and the other is a physical unit.

__mul__

__mul__(other)

Multiply this measurement by another measurement or by a numeric scalar.

Parameters:

Name Type Description Default
other Measurement | Decimal | float | int

The multiplier. When a Measurement is provided, units are combined according to unit algebra; when a numeric scalar is provided, the magnitude is scaled and the unit is preserved.

required

Returns:

Name Type Description
Measurement Measurement

The product as a Measurement with the resulting magnitude and unit.

Raises:

Type Description
CurrencyScalarOperationError

If both operands are currency measurements (multiplying two currencies is not allowed).

MeasurementScalarTypeError

If other is not a Measurement or a supported numeric type.

__truediv__

__truediv__(other)

Divide this measurement by another measurement or by a numeric scalar.

Parameters:

Name Type Description Default
other Measurement | Decimal | float | int

The divisor; when a Measurement, must be compatible (currencies require same unit).

required

Returns:

Name Type Description
Measurement Measurement

The quotient as a new Measurement. If other is a Measurement the result carries the derived units; if other is a scalar the result retains this measurement's unit.

Raises:

Type Description
CurrencyMismatchError

If both operands are currencies with different units.

MeasurementScalarTypeError

If other is not a Measurement or a numeric type.

__str__

__str__()

Return a human-readable string of the measurement, including its unit when not dimensionless.

Returns:

Type Description
str

A string formatted as " " for measurements with a unit, or as "" for dimensionless measurements.

__repr__

__repr__()

Return a detailed representation suitable for debugging.

Returns:

Name Type Description
str str

Debug-friendly notation including magnitude and unit.

__radd__

__radd__(other)

Allow right-side addition so sum() treats 0 as the neutral element.

Parameters:

Name Type Description Default
other Any

Left operand supplied by Python's arithmetic machinery; typically 0 when used with sum().

required

Returns:

Name Type Description
Measurement Measurement

self if other is 0, otherwise the result of adding other to self.

__rsub__

__rsub__(other)

Support right-side subtraction.

Parameters:

Name Type Description Default
other Any

Left operand supplied by Python's arithmetic machinery; typically 0 when used with sum().

required

Returns:

Name Type Description
Measurement Measurement

Result of subtracting self from other.

Raises:

Type Description
TypeError

If other is not a Measurement instance.

__rmul__

__rmul__(other)

Support right-side multiplication.

Parameters:

Name Type Description Default
other Any

Left operand supplied by Python's arithmetic machinery.

required

Returns:

Name Type Description
Measurement Measurement

Result of multiplying other by self.

__rtruediv__

__rtruediv__(other)

Support right-side division.

Parameters:

Name Type Description Default
other Any

Left operand supplied by Python's arithmetic machinery.

required

Returns:

Name Type Description
Measurement Measurement

Result of dividing other by self.

Raises:

Type Description
TypeError

If other is not a Measurement instance.

__ge__

__ge__(other)

Check whether the measurement is greater than or equal to another value.

Parameters:

Name Type Description Default
other Any

Measurement or compatible representation used in the comparison.

required

Returns:

Name Type Description
bool bool

True when the measurement is greater than or equal to other.

Raises:

Type Description
TypeError

If other cannot be interpreted as a measurement.

ValueError

If units are incompatible.

__hash__

__hash__()

Compute a hash using the measurement's magnitude and unit.

Returns:

Name Type Description
int int

Stable hash suitable for use in dictionaries and sets.

general_manager.measurement.measurement_field.MeasurementField

Bases: Field

__init__

__init__(
    base_unit,
    *args,
    null=False,
    blank=False,
    editable=True,
    unique=False,
    **kwargs
)

Create a MeasurementField configured with a canonical base unit and paired backing columns.

Initializes the field's canonical base unit and derived dimensionality, records the editable flag, constructs the Decimal-backed value column and Char-backed unit column using the provided null/blank/editable/unique settings, and forwards remaining arguments to the base Field constructor.

Parameters:

Name Type Description Default
base_unit str

Canonical unit used to normalize and store measurements.

required
*args Any

Positional arguments forwarded to the base Field implementation.

()
null bool

If True, the backing columns may be NULL in the database.

False
blank bool

If True, forms may accept an empty value for this field.

False
editable bool

If False, assignments through the model API will be rejected.

True
unique bool

If True, the backing value column is created with a unique constraint.

False
**kwargs Any

Additional keyword arguments forwarded to the base Field implementation.

{}

contribute_to_class

contribute_to_class(
    cls, name, private_only=False, **kwargs
)

Attach the measurement field and its backing value and unit fields to the model and install the descriptor.

Parameters:

Name Type Description Default
cls type[Model]

Model class receiving the field.

required
name str

Attribute name to use on the model for this field.

required
private_only bool

Whether the field should be treated as private.

False
kwargs object

Additional options forwarded to the base implementation.

{}

get_col

get_col(alias, output_field=None)

Return a Col expression that references this field's backing value column for ORM queries.

Parameters:

Name Type Description Default
alias str

Table alias to use for the column reference.

required
output_field Field | None

Optional field to use as the expression's output type; defaults to the backing value field.

None

Returns:

Name Type Description
Col Col

Column expression targeting the numeric backing value field.

get_lookup

get_lookup(lookup_name)

Retrieve a lookup class from the underlying decimal field.

Parameters:

Name Type Description Default
lookup_name str

Name of the lookup to resolve.

required

Returns:

Type Description
type[Lookup]

type[models.Lookup]: Lookup class implementing the requested comparison.

get_transform

get_transform(lookup_name)

Return a transform callable provided by the underlying decimal field.

Parameters:

Name Type Description Default
lookup_name str

Name of the transform to resolve.

required

Returns:

Type Description
type[Transform] | None

models.Transform | None: Transform class when available; otherwise None.

deconstruct

deconstruct()

Return serialization details so migrations can reconstruct the field.

Ensures the required base_unit argument is preserved alongside the standard Django field options emitted by the base implementation.

db_type

db_type(connection)

Signal to Django that the field does not map to a single column.

Parameters:

Name Type Description Default
connection BaseDatabaseWrapper

Database connection used for schema generation.

required

Returns:

Type Description
None

None

run_validators

run_validators(value)

Execute all configured validators when a measurement is provided.

Parameters:

Name Type Description Default
value Measurement | None

Measurement instance that should satisfy field validators.

required

Returns:

Type Description
None

None

clean

clean(value, model_instance=None)

Validate a measurement value before it is saved to the model.

Parameters:

Name Type Description Default
value Measurement | None

Measurement provided by forms or assignment.

required
model_instance Model | None

Instance associated with the field, when available.

None

Returns:

Type Description
Measurement | None

Measurement | None: The validated measurement value, or None if the input was None.

Raises:

Type Description
ValidationError

If validation fails due to null/blank constraints or validator errors.

to_python

to_python(value)

Convert database values back into Python objects.

Parameters:

Name Type Description Default
value Any

Value retrieved from the database.

required

Returns:

Name Type Description
Any Measurement | str | None

Original value without modification.

get_prep_value

get_prep_value(value)

Serialise a measurement for storage by converting it to the base unit magnitude.

Parameters:

Name Type Description Default
value Measurement | str | None

Value provided by the model or form.

required

Returns:

Type Description
Decimal | None

Decimal | None: Decimal magnitude in the base unit, or None when no value is supplied.

Raises:

Type Description
ValidationError

If the value cannot be interpreted as a compatible measurement.

__get__

__get__(instance, owner=None)

Resolve the field value on an instance, reconstructing the measurement when possible.

Parameters:

Name Type Description Default
instance Model | None

Model instance owning the field, or None when accessed on the class.

required
owner type[Model] | None

Model class owning the descriptor.

None

Returns:

Type Description
MeasurementField | Measurement | None

MeasurementField | Measurement | None: Descriptor when accessed on the class, reconstructed measurement for instances, or None when incomplete.

__set__

__set__(instance, value)

Set a measurement on a model instance after validating editability, type, and unit compatibility.

Parameters:

Name Type Description Default
instance Model

Model instance receiving the value.

required
value Measurement | str | None

A Measurement, a string parseable to a Measurement, or None to clear the field.

required

Raises:

Type Description
MeasurementFieldNotEditableError

If the field is not editable.

ValidationError

If the value is not a Measurement (or valid parseable string), if currency unit rules are violated, or if the unit is incompatible with the field's base unit.

validate

validate(value, model_instance=None)

Enforce null/blank constraints and run validators on the provided value.

Parameters:

Name Type Description Default
value Measurement | None

Measurement value under validation.

required
model_instance Model | None

Instance owning the field; unused but provided for API compatibility.

None

Returns:

Type Description
None

None

Raises:

Type Description
ValidationError

If the value violates constraint or validator requirements.