CalculationModel Internals
CalculationModel extends LexModel with a built-in state machine and a calculate() hook. It's the base class for any model that performs on-demand computation — upload processing, report generation, data transformations, etc.
Browse the full source on GitHub.
from lex.core.models.CalculationModel import CalculationModelThe State Machine
Every CalculationModel has an is_calculated field that transitions through five states:
stateDiagram-v2
[*] --> NOT_CALCULATED : Record created
NOT_CALCULATED --> IN_PROGRESS : "Calculate" clicked
IN_PROGRESS --> SUCCESS : calculate() completed
IN_PROGRESS --> ERROR : Exception raised
IN_PROGRESS --> ABORTED : Manually aborted
ERROR --> IN_PROGRESS : Retry
SUCCESS --> IN_PROGRESS : Recalculate
ABORTED --> IN_PROGRESS : RetryState | Constant | Meaning |
|---|---|---|
|
| Default — record exists but hasn't been processed |
|
| Calculation is running (triggers |
|
| Calculation completed without error |
|
| An exception was raised — error details are stored on the record |
|
| Calculation was manually cancelled |
The is_calculated field is not editable in the UI — it's managed entirely by the framework. When a user clicks Calculate ▶️ in the frontend, the framework sets is_calculated = IN_PROGRESS, which triggers the calculate_hook.
calculate() Method
Override this method with your business logic. The framework handles everything else:
class BudgetSummary(CalculationModel):
team = models.ForeignKey(Team, on_delete=models.CASCADE)
total_expenses = models.DecimalField(max_digits=12, decimal_places=2, default=0)
def calculate(self):
expenses = Expense.objects.filter(employee__team=self.team)
self.total_expenses = expenses.aggregate(
total=models.Sum("amount")
)["total"] or 0What you don't need to write:
Concern | Handled By |
|---|---|
| Framework saves automatically after |
Error handling | Framework catches exceptions and sets |
State transitions | Lifecycle hooks manage the |
Logging context | LexLogger automatically links to the current calculation |
Concurrency | Runs inside |
| Any records you save inside |
The legacy method name
update()is also supported — if you overrideupdate()instead ofcalculate(), the framework will call it. We recommend usingcalculate()for new code.
Atomic vs Non-Atomic
By default, calculate() runs inside a Django transaction.atomic() block — if anything fails, all database changes are rolled back. To opt out (for long-running calculations that should commit incrementally), set:
class LargeImport(CalculationModel):
is_atomic = False
def calculate(self):
# Commits happen as you go — no rollback on failure
...Celery Integration
In production, calculations can be dispatched to Celery workers for background/parallel processing. The framework checks two things automatically:
- Is the
CELERY_ACTIVEenvironment variable set totrue? - Does the
calculate()method have a.delay()attribute (i.e., is it decorated with@lex_shared_task)?
If both are true, the calculation is dispatched to a Celery worker via calc_and_save.delay(). Otherwise, it runs synchronously in the request thread.
To make a calculation Celery-capable, decorate it with @lex_shared_task:
from lex.lex_app.celery_tasks import lex_shared_task
class HeavyReport(CalculationModel):
@lex_shared_task
def calculate(self):
...@lex_shared_task wraps your method with context-aware dispatch, automatic status callbacks (SUCCESS / ERROR), and audit logging context propagation to worker processes. Without the decorator, calculate() always runs synchronously — even when CELERY_ACTIVE=true.
Set
CELERY_ACTIVE=truein your project's.envfile to enable Celery dispatch. You also need a running Redis instance (or Memurai on Windows) as the message broker.
See Celery & Async Calculations for the full setup guide — environment variables, running workers, and the WaitForTasks / FireAndForget context managers.
Nested Calculations
When a parent calculation triggers a child, wrap the child execution in model_logging_context to preserve the log hierarchy:
from lex.audit_logging.utils.ModelContext import model_logging_context
class ParentReport(CalculationModel):
def calculate(self):
child = ChildReport.objects.get(pk=self.child_id)
with model_logging_context(child):
child.is_calculated = "IN_PROGRESS"
child.save()Batch Generation with CalculatedModelMixin
When you need to generate many records from dimensional combinations (e.g., one liability per award per upload), use CalculatedModelMixin instead. It provides a combination engine, duplicate handling, and parallel dispatch — see CalculatedModelMixin Internals for the API reference and Batch Calculations for the full guide.
Inherited Features
Since CalculationModel extends LexModel, your calculation models also get:
created_by/edited_bytrackingpre_validation()/post_validation()hooks- All
permission_*()methods streamlit_main()/streamlit_class_main()for dashboards- Full bitemporal history (unless listed in
untracked_models)
Quick Reference
from lex.core.models.CalculationModel import CalculationModel
from lex.audit_logging.handlers.LexLogger import LexLogger
class MyCalculation(CalculationModel):
# Define your fields
input_field = models.ForeignKey(...)
result_field = models.DecimalField(...)
def calculate(self):
# 1. Query data
# 2. Compute results
# 3. Assign to self.result_field (framework saves)
# 4. Log with LexLogger (optional)
logger = LexLogger()
logger.add_heading("Results")
logger.add_text("Done!")
logger.log()Was this helpful?
Your feedback shapes what we write next.
