Observation Definition
Technical reference for the ObservationDefinition module in Care EMR. For the plain-language view, see the Observation Definition concept.
An ObservationDefinition is master data, usually facility-scoped, that describes how one observation is captured: its code, data type, unit, method, body site, components and interpretation rules (qualified ranges). Activity definitions and diagnostic reports of the same facility use it, and each Observation recorded from it links back to it.
The Django model is storage only: code, body_site, method, permitted_unit, component and qualified_ranges are JSONFields. Their shape, the enums, the value-set bindings and the read and write contracts live in the Pydantic resource specs, built on EMRResource.
Source:
- Model:
care/emr/models/observation_definition.py - Resource spec:
care/emr/resources/observation_definition/spec.py - Viewset:
care/emr/api/viewsets/observation_definition.py - Authorization:
care/security/authorization/observation_definition.py - Permissions:
care/security/permissions/observation_definition.py - Interpretation evaluator:
care/utils/evaluators/interpretation_evaluator.py - Helper:
care/emr/resources/observation_definition/observation.py
Models
| Model | Purpose |
|---|---|
ObservationDefinition | Master-data definition of how an observation is coded, typed, measured and interpreted |
ObservationDefinition extends SlugBaseModel, which sets FACILITY_SCOPED = True and adds the slug helpers. SlugBaseModel extends EMRBaseModel, which adds history, meta, created_by and updated_by. The shared BaseModel underneath adds external_id, created_date, modified_date and the soft-delete flag deleted.
ObservationDefinition fields
Identity & scope
| Field | Type | Notes |
|---|---|---|
facility | FK → Facility (PROTECT) | Nullable, default=None. Set: the definition belongs to that facility. null: instance-wide. Excluded from the base spec (__exclude__ = ["facility"]); the create spec resolves it from the facility UUID; update cannot change it |
version | IntegerField | Default 1. Read-only: only ObservationDefinitionReadSpec has it |
slug | CharField(255) | Set from slug_value, then namespaced by the viewset. See Slug behaviour |
title | CharField(1024) | Required. Display name of the definition |
status | CharField(255) | Required. ObservationStatusChoices; see Status values. There is no delete endpoint: retire by setting retired |
description | TextField | Required |
derived_from_uri | TextField (not nullable) | Optional in the spec (str | None, default None). The facility form has no field for it |
Coding & measurement
| Field | Type | Notes |
|---|---|---|
category | CharField(255) | Nullable in the model; required in the API as ObservationCategoryChoices. See Category values |
code | JSONField | Required. Coding bound to system-observation (LOINC). See Coding shape |
permitted_data_type | CharField(100) | Required. QuestionType; see Permitted data type values. group, display and url are rejected |
body_site | JSONField | Nullable. Coding bound to system-body-site-observation (SNOMED CT) |
method | JSONField | Nullable. Coding bound to system-collection-method (SNOMED CT) |
permitted_unit | JSONField | Nullable. Coding bound to system-ucum-units (UCUM) |
Components & ranges
| Field | Type | Notes |
|---|---|---|
component | JSONField | Nullable. list[ObservationDefinitionComponentSpec] | None. Several values under one definition (systolic and diastolic, for example), each with its own code, permitted_data_type, permitted_unit and qualified_ranges. See ObservationDefinitionComponentSpec |
qualified_ranges | JSONField | Model default list. Required in the API as list[QualifiedRangeSpec]; may be empty. The interpretation rules. See QualifiedRangeSpec |
Enum values
Status values
ObservationStatusChoices, bound to status.
| Value |
|---|
draft |
active |
retired |
unknown |
Category values
ObservationCategoryChoices, bound to category.
| Value |
|---|
social_history |
vital_signs |
imaging |
laboratory |
procedure |
survey |
exam |
therapy |
activity |
Permitted data type values
QuestionType (from questionnaire/spec.py), bound to permitted_data_type on the definition and on each component. validate_question_type rejects group, display and url with "Cannot create a definition with this type". The facility form offers seven of the allowed values: boolean, decimal, integer, dateTime, time, string and quantity.
| Value | Allowed for a definition |
|---|---|
group | No (rejected) |
boolean | Yes |
decimal | Yes |
integer | Yes |
string | Yes |
text | Yes |
display | No (rejected) |
date | Yes |
dateTime | Yes |
time | Yes |
choice | Yes |
url | No (rejected) |
quantity | Yes |
structured | Yes |
JSON field shapes (nested specs)
Coding shape
The coded fields (code, body_site, method, permitted_unit) store a Coding object. The spec binds each one to a value set through ValueSetBoundCoding[<slug>], and Care refuses a code that is not in that value set ("Code does not exist in the valueset").
Coding {
system: str | null = null
version: str | null = null
code: str # required
display: str | null = null
} # extra="forbid": unknown keys rejected
| Field | Bound value set (slug) | Code system |
|---|---|---|
code | system-observation | LOINC (http://loinc.org) |
body_site | system-body-site-observation | SNOMED CT: a listed set of concepts plus every concept under 442083009 |
method | system-collection-method | SNOMED CT |
permitted_unit | system-ucum-units | UCUM (http://unitsofmeasure.org) |
ObservationDefinitionComponentSpec
Element of the component list: one per value when a definition carries several.
ObservationDefinitionComponentSpec {
code: ValueSetBoundCoding[system-observation] # required
permitted_data_type: QuestionType # required; group/display/url rejected
permitted_unit: ValueSetBoundCoding[system-ucum-units] | null = null
qualified_ranges: list[QualifiedRangeSpec] # required
}
Care interprets a result component with the rules of the definition component whose code.code is the same.
QualifiedRangeSpec
Element of qualified_ranges, on the definition and on each component. A rule is either numeric (ranges) or coded (value sets), never both. The facility form creates only numeric rules.
QualifiedRangeSpec {
title: str | null = null
conditions: list[EvaluatorConditionSpec] = []
ranges: list[NumericRangeSpec] = []
default_interpretation: InterpretationSpec | null = null
normal_coded_value_set: str | null = ""
critical_coded_value_set: str | null = ""
abnormal_coded_value_set: str | null = ""
valueset_interpretation: list[ValueSetInterpretationSpec] = []
}
validate_categorical_or_numeric enforces:
- Either
rangesor at least one coded value set orvalueset_interpretationis required. rangesand coded value sets cannot both appear.- Numeric
rangesmust not overlap. The check sorts bymin(a missingminormaxcounts as -∞ or +∞) and refusescurr_min < prev_max, so ranges that only touch are accepted. - Coded value-set slugs must be unique within a rule ("Duplicate valueset interpretations detected").
NumericRangeSpec
NumericRangeSpec {
interpretation: InterpretationSpec # required
min: Decimal(max_digits=20, decimal_places=6) | null = null
max: Decimal(max_digits=20, decimal_places=6) | null = null
}
At least one of min and max is required (validate_range).
InterpretationSpec
InterpretationSpec {
display: str # required
icon: str | null = ""
color: str | null = ""
highlight: bool | null = false
code: Coding | null = {}
}
The fallback switch of the facility form saves default_interpretation as { display: "", highlight: true }.
ValueSetInterpretationSpec
ValueSetInterpretationSpec {
interpretation: InterpretationSpec # required
valuset: str # value-set slug; note the spelling "valuset"
}
The frontend type for this shape uses the key valueset, which does not match. The facility form does not create coded rules.
EvaluatorConditionSpec
Element of QualifiedRangeSpec.conditions. An unknown metric is refused with "Invalid metric", and the metric's evaluator validates operation and value. See Condition metrics.
EvaluatorConditionSpec {
metric: str # must resolve in EvaluatorMetricsRegistry
operation: str
value: dict | str
}
Related models
Facility ──< ObservationDefinition ObservationDefinition.facility: FK, PROTECT, nullable
ObservationDefinition ──< Observation Observation.observation_definition: FK, CASCADE, nullable
ActivityDefinition.observation_result_requirements: list of ObservationDefinition ids, same facility
Resource specs (API schema)
All specs subclass BaseObservationDefinitionSpec, an EMRResource with __model__ = ObservationDefinition and __exclude__ = ["facility"].
| Spec class | Role | Notable fields / behaviour |
|---|---|---|
BaseObservationDefinitionSpec | Shared base | id, title, status, description, category, code, permitted_data_type, component, body_site, method, permitted_unit, derived_from_uri, qualified_ranges. Runs validate_data_type and validate_qualified_ranges_consistency |
ObservationDefinitionCreateSpec | Write · create | Adds facility: UUID4 | null (must exist: "Facility not found") and slug_value: SlugType. perform_extra_deserialization resolves the facility and sets obj.slug = slug_value |
ObservationDefinitionUpdateSpec | Write · update | Adds slug_value: SlugType; perform_extra_deserialization sets obj.slug = slug_value. It cannot change the facility |
ObservationDefinitionReadSpec | Read · list & retrieve | Adds version, facility (serialized with FacilityBareMinimumSpec), slug_config (parse_slug(slug)) and slug; id is the external_id |
Notes:
- Value-set bindings:
code,body_site,methodandpermitted_unit, and the componentcodeandpermitted_unit, areValueSetBoundCoding[...]. Care checks the submitted coding against the bound value set. - Data-type guard:
permitted_data_type, on the definition and on each component, rejectsgroup,displayandurl. - Rule kind consistency:
validate_qualified_ranges_consistencyrequires all rules of one definition to be the same kind: all numeric or all coded. It does not stop rules on both the definition and its components; only the facility form does. slug_value:SlugType, 5–50 characters, pattern^[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]$. Stored namespaced inslug.- Metadata:
__store_metadata__keeps theEMRResourcedefault,False.
Methods & save behaviour
ObservationDefinition adds no methods of its own. The slug helpers come from SlugBaseModel, and the viewset applies the namespacing on create and update.
Slug behaviour
The viewset's recalculate_slug rewrites slug on every create and update:
facility-scoped: f-<facility.external_id>-<slug_value>
instance-wide: i-<slug_value>
calculate_slug()returns thef-form when the model has a facility, otherwise thei-form.parse_slug(slug)returns{"facility": <uuid>, "slug_value": <bare slug>}for anf-slug and{"slug_value": <bare slug>}for ani-slug; anything else raises "Invalid slug".ObservationDefinitionReadSpecexposes the result asslug_config.- The lookup field is
slug, so the retrieve, update and upsert calls take the stored, namespaced slug. - Create and update refuse a slug that already exists in the same scope (compared case-insensitively) with "Slug already exists.".
Save behaviour
- Care writes only the fields whose value differs from the schema default (
exclude_defaults=True). A field sent asnullwhere the default isnullis not written, so it keeps its stored value. - Retiring is an update with
statusset toretired. The inheriteddeletedflag is a soft delete that the default manager hides; no endpoint sets it.
API integration notes
Endpoints
The viewset is registered at the top level, not under a facility. It has no destroy action, so the API has no delete.
| Method & path | Action | Notes |
|---|---|---|
GET /api/v1/observation_definition/ | list | Filters: facility (UUID), category and status (exact, case-insensitive), title (contains, case-insensitive). Ordering: created_date, modified_date |
GET /api/v1/observation_definition/{slug}/ | retrieve | Lookup by slug |
POST /api/v1/observation_definition/ | create | Body: ObservationDefinitionCreateSpec |
PUT or PATCH /api/v1/observation_definition/{slug}/ | update | Body: ObservationDefinitionUpdateSpec. PATCH runs the same full update |
POST /api/v1/observation_definition/upsert/ | upsert | datapoints: one with id (the slug) is an update, one without is a create. Each runs the create or update checks |
GET /api/v1/observation_definition/metrics/ | metrics | Every registered condition metric: name, verbose name, context and allowed operations. Sign-in only |
Authorization
| Action | Permission checked | Where it must be held |
|---|---|---|
list with facility | Can Read Observation Definition | Any organization of that facility (root or department). Returns only that facility's definitions |
list without facility | None (sign-in only) | Returns only instance-wide definitions |
| retrieve a facility definition | Can Read Observation Definition | Any organization of the definition's facility |
| retrieve an instance-wide definition | None (sign-in only) | Open to every signed-in user |
| create, update or upsert a facility definition | Can Create Observation Definition on Facility | The facility's root organization (org_type root, named "Administration"). A role held only in a department fails with 403 "Access Denied to Observation Definition" |
A facility user cannot create or update an instance-wide definition (no facility): the request fails with 403 "Access Denied to Observation Definition".
Default roles: Can Create Observation Definition on Facility is held by Facility Admin. Can Read Observation Definition is held by Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer and Pharmacist. These are defaults: the sync command rewrites the system roles from the code, and a deployment can add custom roles.
The facility screens check no permission themselves; every gate is in the backend.
Interpretation evaluation
InterpretationEvaluator applies the rules of a definition to a result:
- Rules are checked in list order. The first rule whose conditions all match is used, and later rules are never checked, even when that rule gives no interpretation. A rule with no conditions always matches.
- In a numeric rule, ranges are checked in list order, and the first range with
min <= value <= maxgives the interpretation. Both ends are inclusive; a missing bound is open-ended. - In a coded rule, the result's coding is checked against
normal_coded_value_set,critical_coded_value_setandabnormal_coded_value_set(fixed displays "Normal", "Critical" and "Abnormal"), then eachvalueset_interpretationin order. - If nothing in the rule matches the value, the rule's
default_interpretationis used; without one, the result has no interpretation. DiagnosticReportViewSet.upsert_observationsrunscompute_observation_interpretationfor each observation linked to a definition, when it is created or updated. It stores the result on the observation asinterpretationandreference_range. Each component value uses the rules of the definition component with the samecode.code.
Condition metrics
Metric (name) | Verbose name | Operations | Notes |
|---|---|---|---|
patient_age | Patient Age | in_range, equality | Value unit years (default), months or days; in_range includes both ends |
patient_gender | Patient Gender | equality | Patient context |
encounter_class | Encounter Class | equality | |
encounter_tag | Encounter Tag | has_tag | value_type selects the encounter's tags (default) or the patient's tags. Matches when any listed tag is present and not expired |
patient_tag | Patient Tag | has_tag | The facility form does not offer this metric |
Other notes
- The facility binding is write-once: create resolves
facility, and update cannot change it. - Activity definitions and diagnostic reports accept only definitions of their own facility, and do not check the definition's status. The facility pickers offer only
activedefinitions. convert_od_to_observation(observation.py) builds anObservationfor an encounter from a definition, with the definition'scategoryandcodeand the statusfinal.
Related
- Concept: Observation Definition
- Reference: Observation
- Reference: Diagnostic Report
- Reference: Activity Definition
- Reference: Valueset
- Reference: Base model
- Source: observation_definition.py (model)
- Source: observation_definition/spec.py (resource spec)
- Source: observation/valueset.py (bound value sets)