Calculations
A CalculationModel is a model whose records can be "calculated" on demand. When a user clicks Calculate in the frontend, the framework transitions the record to IN_PROGRESS, calls your calculate() method, and then transitions to SUCCESS or ERROR depending on the outcome. You only write the business logic — everything else is handled for you.
Defining a Calculation Model
Inherit from CalculationModel and implement calculate():
from lex.core.models.CalculationModel import CalculationModel
from django.db import models
class CalculateNAV(CalculationModel):
quarter = models.ForeignKey('Quarter', on_delete=models.CASCADE)
nav_value = models.DecimalField(max_digits=19, decimal_places=2, null=True)
def calculate(self):
investments = Investment.objects.filter(quarter=self.quarter)
total = sum(inv.market_value for inv in investments)
self.nav_value = totalThat's it. No decorators, no manual self.save(), no recursion guards. The framework handles state management, error capture, and saving automatically.
The State Machine
The is_calculated field is a state machine with clear transitions:
stateDiagram-v2
[*] --> NOT_CALCULATED : Record created
NOT_CALCULATED --> IN_PROGRESS : User clicks "Calculate"
IN_PROGRESS --> SUCCESS : Completed without errors
IN_PROGRESS --> ERROR : Exception occurred
IN_PROGRESS --> ABORTED : Manually cancelled
ERROR --> IN_PROGRESS : Retry
SUCCESS --> IN_PROGRESS : Recalculate
ABORTED --> IN_PROGRESS : RetryState | Meaning |
|---|---|
| Record exists, no calculation run yet |
| Calculation is currently running |
| Completed without errors |
| An exception occurred (details stored in |
| Manually cancelled |
What You Get Automatically
You don't need to define or manage any of the following — they're inherited from CalculationModel:
is_calculated— the state field- Recursion guard — prevents re-entrant calculation loops
- Error capture — exceptions are caught and stored in
calculation_error_message - Auto-save — the record is saved automatically after
calculate()returns - Celery support — dispatch to Celery workers for parallel execution
- System-save attribution — any records you save inside
calculate()won't have theiredited_by/edited_atstamped with the triggering user; those saves are treated as system-triggered, not direct user edits
Need to generate many records at once?
If your calculation creates one output per combination (e.g., one liability per award per upload), see Batch Calculations —CalculatedModelMixinhandles the combination generation, deduplication, and parallel dispatch for you.
How the state machine works internally
TheCalculationModelbase class uses@hook(AFTER_UPDATE)on theis_calculatedfield. When it transitions toIN_PROGRESS, the framework callscalculate_hook()which:
- Sets
is_calculated = IN_PROGRESS- Decides whether to run synchronously or via Celery (
should_use_celery())- Calls your
calculate()method- On success: sets
is_calculated = SUCCESSand saves- On exception: sets
is_calculated = ERROR, stores the traceback incalculation_error_message, and savesYou never need to manage this yourself.
Another Example
class CalculateBalanceSheet(CalculationModel):
quarter = models.ForeignKey('Quarter', on_delete=models.CASCADE)
total_assets = models.DecimalField(max_digits=19, decimal_places=2, null=True)
def calculate(self):
assets = Asset.objects.filter(quarter=self.quarter)
self.total_assets = assets.aggregate(Sum('value'))['value__sum']Migrating from V1?
If you're coming fromConditionalUpdateMixin, here's what changes:
Aspect
V1 (Old)
Current
Base class
ConditionalUpdateMixin
CalculationModelMethod name
update()
calculate()Decorator
@ConditionalUpdateMixin.conditional_calculationNot needed
State field
Boolean
is_calculatedEnum with 5 states
Recursion guard
Manual
dont_updateflagAutomatic
Error handling
Manual
try/catchAutomatic (stored in
calculation_error_message)Save
Manual
self.save()Automatic after method returns
Migration Checklist
Change base class:
ConditionalUpdateMixin→CalculationModelRemove the
@conditional_calculationdecoratorRename method:
update()→calculate()Remove
is_calculated = IsCalculatedField(...)(inherited automatically)Remove
calculate = CalculateField(...)(inherited automatically)Remove the
dont_updaterecursion guardRemove manual
self.save()calls
Was this helpful?
Your feedback shapes what we write next.
