Skip to content

Models

Base

rn_forge.django.models.base

Abstract Django model building blocks.

BaseModel

Bases: Model, TruncateModelMixin, FixtureModelMixin

Abstract base model with status field and audit timestamps.

Uses :class:NaturalKeyLookupManager; database columns take the field names.

get_attrs(attr_getter)

Return a tuple of attribute values extracted by attr_getter.

get_full_clean_exclude(update_fields=None) classmethod

Return the field names to exclude from full_clean().

natural_key()

Return the current instance values for :meth:natural_keys.

Supports dotted paths and legacy "relation__field" paths. A single value is returned as a one-element tuple.

natural_keys() classmethod

Return the list of field names that form this model's natural key.

The corresponding :meth:natural_key always returns a tuple.

save(*, force_insert=False, force_update=False, using=None, update_fields=None)

Optionally validate the model before saving it.

should_validate_on_save() classmethod

Return whether this model opts into full_clean() during save.

truncate() classmethod

Truncate the table backing this model.

SQLite falls back to DELETE FROM because it lacks TRUNCATE.

DateModel

Bases: BaseModel

Abstract model that adds a single date field to :class:BaseModel.

get_attrs(attr_getter)

Return a tuple of attribute values extracted by attr_getter.

get_full_clean_exclude(update_fields=None) classmethod

Return the field names to exclude from full_clean().

natural_key()

Return the current instance values for :meth:natural_keys.

Supports dotted paths and legacy "relation__field" paths. A single value is returned as a one-element tuple.

natural_keys() classmethod

Return the list of field names that form this model's natural key.

The corresponding :meth:natural_key always returns a tuple.

save(*, force_insert=False, force_update=False, using=None, update_fields=None)

Optionally validate the model before saving it.

should_validate_on_save() classmethod

Return whether this model opts into full_clean() during save.

truncate() classmethod

Truncate the table backing this model.

SQLite falls back to DELETE FROM because it lacks TRUNCATE.

DateRangeModel

Bases: BaseModel

Abstract model with an inclusive date range and an activity property.

end_date is optional; an open-ended range is considered active indefinitely once start_date is reached.

is_date_range_active property

Return True when today falls within [start_date, end_date].

get_attrs(attr_getter)

Return a tuple of attribute values extracted by attr_getter.

get_full_clean_exclude(update_fields=None) classmethod

Return the field names to exclude from full_clean().

natural_key()

Return the current instance values for :meth:natural_keys.

Supports dotted paths and legacy "relation__field" paths. A single value is returned as a one-element tuple.

natural_keys() classmethod

Return the list of field names that form this model's natural key.

The corresponding :meth:natural_key always returns a tuple.

save(*, force_insert=False, force_update=False, using=None, update_fields=None)

Optionally validate the model before saving it.

should_validate_on_save() classmethod

Return whether this model opts into full_clean() during save.

truncate() classmethod

Truncate the table backing this model.

SQLite falls back to DELETE FROM because it lacks TRUNCATE.

FixtureModelMixin

Abstract mixin that declares the natural_keys() contract.

natural_key()

Return the current instance values for :meth:natural_keys.

Supports dotted paths and legacy "relation__field" paths. A single value is returned as a one-element tuple.

natural_keys() classmethod

Return the list of field names that form this model's natural key.

The corresponding :meth:natural_key always returns a tuple.

NaturalKeyLookupManager

Bases: Manager['BaseModel']

Manager that supports natural-key deserialization in Django fixtures.

The model must implement :meth:FixtureModelMixin.natural_keys.

TruncateModelMixin

Mixin that adds a truncate() class method for DDL-level table clearing.

Useful for test teardown. Issues a raw TRUNCATE TABLE statement; use with care in production.

truncate() classmethod

Truncate the table backing this model.

SQLite falls back to DELETE FROM because it lacks TRUNCATE.

Concurrency and immutability

rn_forge.django.models.concurrency

Opt-in optimistic-concurrency and immutability model mixins.

ImmutableModelMixin

Bases: Model

Abstract mixin that rejects post-creation mutation and deletion.

Saving a changed row raises :class:rn_forge.web.DomainConflict; deleting always raises. Queryset-level update() and delete() bypass the guard.

delete(using=None, keep_parents=False)

Always raise: an immutable row is never deleted.

save(*, force_insert=False, force_update=False, using=None, update_fields=None)

Reject a change to any guarded field, then delegate to super().save().

VersionedModelMixin

Bases: Model

Abstract mixin adding an optimistic-concurrency version counter.

Existing rows increment from the loaded version, including partial saves. A concurrent update raises :class:rn_forge.web.VersionConflict.

save(*, force_insert=False, force_update=False, using=None, update_fields=None)

Bump version on update, then delegate to super().save().

Soft delete

rn_forge.django.models.soft_delete

Soft-delete model mixin and queryset (AIP-164).

SoftDeleteModelMixin

Bases: Model

Abstract mixin adding a nullable, indexed delete_time column.

List it before :class:~rn_forge.django.models.BaseModel so that its manager, which adds .live() and .deleted() to the natural-key manager, is the model's default. That manager is not filtered. Saving a :class:~rn_forge.django.models.VersionedModelMixin model through :meth:soft_delete or :meth:undelete bumps its version as any save does.

get_delete_time()

Return the time :meth:soft_delete records; the current UTC time.

soft_delete(*, actor)

Set delete_time, record actor in updated_by and save.

undelete(*, actor)

Clear delete_time, record actor in updated_by and save.

SoftDeleteQuerySet

Bases: QuerySet[Any]

A queryset that can select live or soft-deleted rows.

deleted()

Return the rows whose delete_time is set.

live()

Return the rows whose delete_time is None.

Sequences

rn_forge.django.models.sequences

Database-backed generation of human-readable sequence codes.

AbstractSequenceCounter

Bases: Model

Abstract counter table backing the non-PostgreSQL sequence path.

SequenceGenerator(name, *, counter_model, prefix='', formatter=None, using=None)

Allocate gap-free, human-readable codes from a named database sequence.

Parameters:

Name Type Description Default
name str

The sequence name. Must match [a-z][a-z0-9_]* (at most 63 characters). The attribute may be reassigned; the current value is validated again, and quoted as an identifier, before each PostgreSQL statement.

required
counter_model type[AbstractSequenceCounter]

The consumer's concrete :class:AbstractSequenceCounter.

required
prefix str

Passed to formatter.

''
formatter Callable[[str, int], str] | None

(prefix, value) -> code. Defaults to :func:default_code_formatter.

None
using str | None

A database alias. Defaults to the router's write database for counter_model.

None

Raises:

Type Description
AppException

name is not a valid sequence name, at construction or when :meth:next_value or :meth:ensure_at_least runs.

ensure_at_least(value)

Raise the floor so the next value is greater than value.

For backfills and imports. A no-op when the current value is already at or above value.

generate()

Allocate the next value and return it formatted.

next_value()

Allocate and return the next raw value.

default_code_formatter(prefix, value)

Return a six-digit value with a prefix, or the raw value without one.

Fields

rn_forge.django.models.fields

Custom Django model fields for rn-forge-django.

EnumField

Bases: EnumFieldBase

CharField that round-trips values through a BaseEnum subclass.

enum_type property

Return the enum class bound to this field.

build(*, enum_type, default=None, **kwargs) classmethod

Build an enum-backed field with sensible defaults.

from_db_value(value, expression, connection)

Convert raw database values to enum members.

get_prep_value(value)

Convert enum members to their raw database values.

to_python(value)

Convert assigned values to enum members when possible.

Enums

rn_forge.django.models.enums

Model-specific enum types for rn-forge-django.

BaseEnum

Bases: TextChoices

TextChoices subclass with reverse-lookup helpers.

get_choices(code_filter=None, name_filter=None) classmethod

Return a list of {"code": ..., "name": ...} dicts.

lookup(key) classmethod

Return {"code": key, "name": ...} for the given enum value.

Status

Bases: BaseEnum

Standard record-status choices.

get_choices(code_filter=None, name_filter=None) classmethod

Return a list of {"code": ..., "name": ...} dicts.

lookup(key) classmethod

Return {"code": key, "name": ...} for the given enum value.

Cache

rn_forge.django.models.cache

Caching helpers for model instance lookup.

ModelLookupCache()

Bulk-load model instances for in-memory lookup by selected fields.

Typical use: load a reference table once at startup, then resolve foreign-key values in O(1) rather than issuing per-row queries.

Example::

cache = ModelLookupCache()
cache.load(Country, "iso_code")
country = cache.get(Country, "AU")

get(model_class, *model_key_values)

Return the cached instance matching model_key_values, or None.

load(model_class, *model_keys)

Bulk-load all instances of model_class and index by model_keys.

set(model_class, instance, *model_keys)

Insert or update instance in the cache.

Utils

rn_forge.django.models.utils

Model serialization helpers for rn-forge-django.

ModelUtils

Utilities for serialising Django model instances.

All methods are static.

as_dict(instance, _seen=None) staticmethod

Return a plain dict of all concrete fields on instance.

Related model instances are recursively converted. Cycles are broken by tracking id() of visited instances; a repeated instance is represented as its string repr instead of being expanded again.

as_json_value(value) staticmethod

Coerce a model field value to a JSON-safe primitive.

  • Primitives (str, int, float, bool, None) are returned unchanged.
  • :class:~datetime.datetime, :class:~datetime.date, and :class:~datetime.time values are converted via .isoformat().
  • All other types fall back to str(value).

to_json(instance, *, indent=None) staticmethod

Serialise instance to a JSON string.