Skip to main content
Version: 3.1

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:

Models​

ModelPurpose
ObservationDefinitionMaster-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​

FieldTypeNotes
facilityFK → 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
versionIntegerFieldDefault 1. Read-only: only ObservationDefinitionReadSpec has it
slugCharField(255)Set from slug_value, then namespaced by the viewset. See Slug behaviour
titleCharField(1024)Required. Display name of the definition
statusCharField(255)Required. ObservationStatusChoices; see Status values. There is no delete endpoint: retire by setting retired
descriptionTextFieldRequired
derived_from_uriTextField (not nullable)Optional in the spec (str | None, default None). The facility form has no field for it

Coding & measurement​

FieldTypeNotes
categoryCharField(255)Nullable in the model; required in the API as ObservationCategoryChoices. See Category values
codeJSONFieldRequired. Coding bound to system-observation (LOINC). See Coding shape
permitted_data_typeCharField(100)Required. QuestionType; see Permitted data type values. group, display and url are rejected
body_siteJSONFieldNullable. Coding bound to system-body-site-observation (SNOMED CT)
methodJSONFieldNullable. Coding bound to system-collection-method (SNOMED CT)
permitted_unitJSONFieldNullable. Coding bound to system-ucum-units (UCUM)

Components & ranges​

FieldTypeNotes
componentJSONFieldNullable. 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_rangesJSONFieldModel 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.

ValueAllowed for a definition
groupNo (rejected)
booleanYes
decimalYes
integerYes
stringYes
textYes
displayNo (rejected)
dateYes
dateTimeYes
timeYes
choiceYes
urlNo (rejected)
quantityYes
structuredYes

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
FieldBound value set (slug)Code system
codesystem-observationLOINC (http://loinc.org)
body_sitesystem-body-site-observationSNOMED CT: a listed set of concepts plus every concept under 442083009
methodsystem-collection-methodSNOMED CT
permitted_unitsystem-ucum-unitsUCUM (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 ranges or at least one coded value set or valueset_interpretation is required.
  • ranges and coded value sets cannot both appear.
  • Numeric ranges must not overlap. The check sorts by min (a missing min or max counts as -∞ or +∞) and refuses curr_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
}
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 classRoleNotable fields / behaviour
BaseObservationDefinitionSpecShared baseid, 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
ObservationDefinitionCreateSpecWrite · createAdds facility: UUID4 | null (must exist: "Facility not found") and slug_value: SlugType. perform_extra_deserialization resolves the facility and sets obj.slug = slug_value
ObservationDefinitionUpdateSpecWrite · updateAdds slug_value: SlugType; perform_extra_deserialization sets obj.slug = slug_value. It cannot change the facility
ObservationDefinitionReadSpecRead · list & retrieveAdds version, facility (serialized with FacilityBareMinimumSpec), slug_config (parse_slug(slug)) and slug; id is the external_id

Notes:

  • Value-set bindings: code, body_site, method and permitted_unit, and the component code and permitted_unit, are ValueSetBoundCoding[...]. Care checks the submitted coding against the bound value set.
  • Data-type guard: permitted_data_type, on the definition and on each component, rejects group, display and url.
  • Rule kind consistency: validate_qualified_ranges_consistency requires 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 in slug.
  • Metadata: __store_metadata__ keeps the EMRResource default, 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 the f- form when the model has a facility, otherwise the i- form.
  • parse_slug(slug) returns {"facility": <uuid>, "slug_value": <bare slug>} for an f- slug and {"slug_value": <bare slug>} for an i- slug; anything else raises "Invalid slug". ObservationDefinitionReadSpec exposes the result as slug_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 as null where the default is null is not written, so it keeps its stored value.
  • Retiring is an update with status set to retired. The inherited deleted flag 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 & pathActionNotes
GET /api/v1/observation_definition/listFilters: facility (UUID), category and status (exact, case-insensitive), title (contains, case-insensitive). Ordering: created_date, modified_date
GET /api/v1/observation_definition/{slug}/retrieveLookup by slug
POST /api/v1/observation_definition/createBody: ObservationDefinitionCreateSpec
PUT or PATCH /api/v1/observation_definition/{slug}/updateBody: ObservationDefinitionUpdateSpec. PATCH runs the same full update
POST /api/v1/observation_definition/upsert/upsertdatapoints: 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/metricsEvery registered condition metric: name, verbose name, context and allowed operations. Sign-in only

Authorization​

ActionPermission checkedWhere it must be held
list with facilityCan Read Observation DefinitionAny organization of that facility (root or department). Returns only that facility's definitions
list without facilityNone (sign-in only)Returns only instance-wide definitions
retrieve a facility definitionCan Read Observation DefinitionAny organization of the definition's facility
retrieve an instance-wide definitionNone (sign-in only)Open to every signed-in user
create, update or upsert a facility definitionCan Create Observation Definition on FacilityThe 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 <= max gives 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_set and abnormal_coded_value_set (fixed displays "Normal", "Critical" and "Abnormal"), then each valueset_interpretation in order.
  • If nothing in the rule matches the value, the rule's default_interpretation is used; without one, the result has no interpretation.
  • DiagnosticReportViewSet.upsert_observations runs compute_observation_interpretation for each observation linked to a definition, when it is created or updated. It stores the result on the observation as interpretation and reference_range. Each component value uses the rules of the definition component with the same code.code.

Condition metrics​

Metric (name)Verbose nameOperationsNotes
patient_agePatient Agein_range, equalityValue unit years (default), months or days; in_range includes both ends
patient_genderPatient GenderequalityPatient context
encounter_classEncounter Classequality
encounter_tagEncounter Taghas_tagvalue_type selects the encounter's tags (default) or the patient's tags. Matches when any listed tag is present and not expired
patient_tagPatient Taghas_tagThe 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 active definitions.
  • convert_od_to_observation (observation.py) builds an Observation for an encounter from a definition, with the definition's category and code and the status final.