Skip to main content
Version: 3.1

Location

FacilityLocation is a node in a facility's building/ward/room/bed tree — where resources sit and where care happens. You work with it when you place an encounter somewhere, scope organization access to part of a facility, or model a site's physical layout.

Source:

Nodes nest: a node may have a parent, and a kind node may have children, so one tree can run from a campus down to a single bed. The create API limits the depth to LOCATION_MAX_DEPTH (default 10). Encounters and organizations attach to nodes. Access granted at a node cascades to its descendants through cached organization IDs, so access checks do not walk the tree on each request. The model maps to the FHIR Location resource.

The Django model is only the storage layer. location_type, metadata, cached_parent_json, and tags_data are opaque JSONFields. The Pydantic resource specs (care/emr/resources/location/spec.py) give location_type its shape, and also define every enum and the read/write schema split. The server alone writes the other three JSON fields. See Resource specs (API schema).

Models​

ModelPurpose
FacilityLocationA node in a facility's location tree (building, ward, room, bed, …)
FacilityLocationOrganizationGrants a FacilityOrganization access to a location
FacilityLocationEncounterRecords how/when an encounter occupied a location (e.g. a bed)

All three extend EMRBaseModel, which supplies external_id, audit fields, and soft-delete semantics.

FacilityLocation fields​

Descriptive​

FieldTypeSpec values / shapeNotes
nameCharField(255)str, requiredNot unique. The model has a sibling-uniqueness helper, but the API does not call it (see validate_uniqueness())
descriptionCharField(255)str, requiredFree-text
statusCharField(255)StatusChoices enumOne of StatusChoices
operational_statusCharField(255)FacilityLocationOperationalStatusChoices enumFHIR operational status code; one of FacilityLocationOperationalStatusChoices
system_availability_statusCharField(255)str (read-only)Server-maintained, derived from encounter association. Resolves to one of LocationAvailabilityStatusChoices (available / reserved)
modeCharField(255)FacilityLocationModeChoices enumkind (a type, e.g. a building/ward) or instance (a single location, e.g. Bed 1). Set on create, then frozen. See FacilityLocationModeChoices
location_typeJSONField (default=dict, nullable)Coding | None (default None)A single FHIR Coding, not a CodeableConcept. Unbound — any coding is accepted
formCharField(255)FacilityLocationFormChoices enumFHIR physical form; one of FacilityLocationFormChoices
inventory_usageCharField(255) (default="none")InventoryUsage enum, default noneHow the location takes part in inventory; one of InventoryUsage. The backend only stores it. care_fe shows inventory screens for any value other than none, and store screens for store. perform_extra_deserialization writes it whenever the request has the key, so an explicit none resets it

Hierarchy & tree caches​

These fields denormalize the tree so descendants are queryable without recursive joins. save() and the cascade own them; never set them from a client.

FieldTypeNotes
parentFK → FacilityLocationSET_NULL, nullable. Immediate parent. Accepted on write as a UUID (parent); on read it's dropped in favour of the serialized parent JSON
root_locationFK → selfCASCADE, related_name="root", nullable. Top of this node's tree. Excluded from specs
has_childrenBooleanFielddefault=False. True when the node has a non-deleted child. Recomputed by sync_children_flags() on every save of the node or of a child. Read-only in list/retrieve specs
has_sub_locationsBooleanFielddefault=False. True when the node has a non-deleted child in kind mode. Recomputed by sync_children_flags(). Read-only; filterable
has_bedsBooleanFielddefault=False. True when the node has a non-deleted child in instance mode. Recomputed by sync_children_flags(). Read-only; filterable
level_cacheIntegerFielddefault=0. Depth in the tree (parent.level_cache + 1)
parent_cacheArrayField[int]Ordered ancestor IDs (parent.parent_cache + [parent.id])
cached_parent_jsonJSONField (default=dict)Serialized parent chain (FacilityLocationListSpec) plus a cache_expiry ISO timestamp. Rebuilt lazily by get_parent_json(), cleared on every update and by the cascade. cache_expiry_days = 15
sort_indexIntegerFielddefault=0. In specs int | None, default 0, constrained 0 ≤ sort_index ≤ 10000 (MIN_SORT_INDEX/MAX_SORT_INDEX). On any save, a value of 0 or null becomes max(sibling sort_index) + 1

Access & encounter​

FieldTypeNotes
facilityFK → facility.FacilityPROTECT. Owning facility. Excluded from specs — resolved from route/context
facility_organization_cacheArrayField[int]default=list. Org IDs that can reach this location; rebuilt by sync_organization_cache()
current_encounterFK → EncounterSET_NULL, nullable, default=None. Populated from FacilityLocationEncounter. Excluded from the base spec; surfaced as serialized JSON in list/retrieve specs
metadataJSONFielddefault=dict. Open bag for deployment-specific data. Not in any spec, so the API neither reads nor writes it

Tags​

FieldTypeNotes
tagsArrayField[int]default=list. Tag config IDs applied to the location. Rendered as tag objects in FacilityLocationListSpec through SingleFacilityTagManager().render_tags()
tags_dataJSONFielddefault=dict. Per-tag metadata keyed by tag ID string: { "<tag_id>": { "expiry": "<datetime>" } }. The tag manager writes an entry when it sets a tag that has an expiry, and removes it when the tag is unset. On read, each rendered tag gets expiry, plus expired: true after that time. Not on any spec

Enum values​

Every enum is a str Enum in care/emr/resources/location/spec.py. Values below are character-for-character from source.

StatusChoices values​

ValueMeaning
activeLocation is active
inactiveLocation is inactive
unknownStatus unknown

FacilityLocationOperationalStatusChoices values​

FHIR HL7 v2 bed/location operational status codes.

CodeMeaning
CClosed
HHousekeeping
OOccupied
UUnoccupied
KContaminated
IIsolated

FacilityLocationModeChoices values​

ValueMeaning
instanceA single, concrete location (e.g. Bed 1). Instances cannot have children
kindA class/type of location (e.g. a ward or building)

FacilityLocationFormChoices values​

FHIR location-physical-type codes.

CodeMeaning
siSite
buBuilding
wiWing
waWard
lvlLevel
coCorridor
roRoom
bdBed
veVehicle
hoHouse
caCabinet
rdRoad
areaArea
jdnJurisdiction
viVirtual

InventoryUsage values​

Used by inventory_usage. Default none.

Value
store
supplier
consumption
adjustment
none

LocationEncounterAvailabilityStatusChoices values​

Used by FacilityLocationEncounter.status — how an encounter occupies a location.

ValueMeaning
plannedOccupancy planned
activeCurrently occupied
reservedReserved
completedOccupancy ended

LocationAvailabilityStatusChoices values​

The server-derived values that system_availability_status resolves to.

ValueMeaning
availableNot actively tied to an encounter
reservedTied to an encounter

Coding shape​

location_type is a single Coding object (extra="forbid"):

Coding {
system: str | None = None
version: str | None = None
code: str # required
display: str | None = None
}

FacilityLocationOrganization​

Links an organization to a location. Users under that organization inherit access to the location and its encounters through whatever role they hold on the organization.

location → FK FacilityLocation (CASCADE)
organization → FK FacilityOrganization (CASCADE)

Saving one of these rows calls location.save() (rebuilding facility_organization_cache), then location.cascade_changes(), which re-saves every descendant in the same request.

The location create body carries organizations (FacilityLocationWriteSpec), but the viewset only authorizes those UUIDs and creates no rows. The organizations_add and organizations_remove actions link and unlink organizations (see API integration notes).

FacilityLocationEncounter​

A bed assignment, in effect: it records how an encounter occupied a location over a time window.

FieldTypeSpecNotes
statusCharField(25)LocationEncounterAvailabilityStatusChoicesOne of planned / active / reserved / completed
locationFK → FacilityLocationexcluded / nestedCASCADE. Surfaced as JSON in ...ListSpecWithLocation
encounterFK → EncounterUUID on write, JSON on readCASCADE. Validated to exist on create
start_datetimeDateTimeFielddatetime (required)Occupancy start
end_datetimeDateTimeField (nullable)datetime | NoneOccupancy end; open-ended when null

FacilityLocation.current_encounter is populated from these rows. After each create, update, or delete of a row, the viewset re-derives the location state (reset_encounter_location_association) under a lock on the location:

  • If the location has an active row, current_encounter is that encounter, system_availability_status is reserved, and the encounter's current_location is this location.
  • If not, current_encounter is null and system_availability_status is available.
  • Any other encounter whose current_location is this location loses it.

The viewset (_validate_data) enforces these rules:

  • A kind location cannot take encounters (Cannot assign encounters to location kind).
  • end_datetime must not be before start_datetime. A completed row requires end_datetime. For an active row, the checks ignore end_datetime.
  • A row must not conflict with another active or planned row on the same location (Conflict in schedule).
  • A location has at most one active row, and an encounter has at most one active location.
  • A completed row cannot change status.
  • Retrieve, update, and delete reject a row that belongs to a different location than the one in the URL.

When an encounter reaches a completed status, close_related_location_from_encounter clears current_encounter on its locations and sets them available. Open rows for the encounter become completed with end_datetime set to now. A location left O (occupied) with no current encounter becomes U (unoccupied).

Methods & save behaviour​

save() side effects​

save() runs inside transaction.atomic():

  1. A save with an empty update_fields list returns without a write.
  2. When parent is set, the parent row is locked (select_for_update).
  3. On insert with a parent, level_cache, root_location, and parent_cache are derived from the parent.
  4. On update, cached_parent_json is cleared so it rebuilds lazily. If update_fields is given, cached_parent_json is added to it.
  5. On any save, a sort_index of 0 or null becomes max(sibling sort_index) + 1.
  6. After super().save(), sync_organization_cache() persists facility_organization_cache through a second save(update_fields=[...]), so each write touches the row twice.
  7. sync_children_flags() then recomputes the child flags of this node and of its parent.

Caches & cascade​

  • sync_organization_cache() — unions the parent's org cache, the org chains of every linked FacilityLocationOrganization, and the facility's default_internal_organization_id, then writes facility_organization_cache.
  • get_parent_json() — returns the cached parent chain, refreshing cached_parent_json (via FacilityLocationListSpec.serialize(parent)) once it expires (cache_expiry_days = 15).
  • sync_children_flags(sync_parent=True) — reads the modes of the node's non-deleted children. It sets has_children (any child), has_sub_locations (a kind child), and has_beds (an instance child) with a queryset update(), then repeats once for the parent.
  • cascade_changes() / handle_cascade(base_location) — handle_cascade has the Celery @app.task decorator, but cascade_changes() calls it directly, so it runs synchronously in the same request. It walks every descendant and calls save(update_fields=["cached_parent_json"]). Each save clears the node's parent JSON and re-runs sync_organization_cache(), so descendants pick up the new organization IDs. It runs when a FacilityLocationOrganization row is saved and after organizations_remove.

validate_uniqueness()​

Classmethod that checks name uniqueness among siblings at the same level_cache within the same root_location — or among root-level locations when there's no root. For a new instance with a parent, level_cache and root_location are computed from that parent before the check runs. It returns True when a duplicate exists.

note

No code calls FacilityLocation.validate_uniqueness(). The location viewset does not check names, so two sibling locations can have the same name. The organization viewsets call their own validate_uniqueness().

Resource specs (API schema)​

The Pydantic specs in care/emr/resources/location/spec.py define the request/response shapes. All extend EMRResource, which provides serialize/de_serialize plus the perform_extra_serialization/perform_extra_deserialization hooks (see base model and base.py).

Location specs​

Spec classRoleExposes / notes
FacilityLocationBaseSpecshared base__model__ = FacilityLocation; id: UUID4 | None. __exclude__ = [parent, facility, organizations, root_location, current_encounter]
FacilityLocationSpecshared fieldsstatus, operational_status, name, description, location_type (Coding | None), form, inventory_usage (InventoryUsage, default none), sort_index (0..10000, default 0). perform_extra_deserialization writes inventory_usage whenever the request has the key
FacilityLocationWriteSpecwrite · createAdds parent: UUID4 | None, organizations: list[UUID4] (required; authorized, not linked), mode: FacilityLocationModeChoices. Validator: a set parent must exist ("Parent not found") and must not be mode = instance ("Instances cannot have children"). perform_extra_deserialization resolves the parent UUID to an FK
FacilityLocationUpdateSpecwrite · updateSame fields as FacilityLocationSpec (an empty subclass), so it has no parent/organizations/mode — hierarchy and mode are fixed after creation
FacilityLocationMinimalListSpecread · nested (encounter current_location)Extends FacilityLocationSpec; adds parent: dict, mode: str, has_children: bool, has_sub_locations: bool, has_beds: bool, system_availability_status: str. perform_extra_serialization sets id = external_id and parent = obj.get_parent_json()
FacilityLocationListSpecread · listExtends minimal; adds current_encounter: dict | None, serialized via EncounterListSpec when present, and tags: list[dict] (default []), rendered via SingleFacilityTagManager().render_tags(obj)
FacilityLocationRetrieveSpecread · detailExtends list; adds created_by/updated_by (via serialize_audit_users)

Encounter-association specs​

Spec classRoleExposes / notes
FacilityLocationEncounterBaseSpecshared base__model__ = FacilityLocationEncounter; id: UUID4 | None. __exclude__ = [encounter, location]
FacilityLocationEncounterCreateSpecwrite · createstatus (LocationEncounterAvailabilityStatusChoices), encounter: UUID4, start_datetime, end_datetime: datetime | None. Validator: encounter must exist. perform_extra_deserialization resolves the encounter UUID to an FK
FacilityLocationEncounterUpdateSpecwrite · updatestatus, start_datetime, end_datetime (no default, so the key is required; null allowed). Encounter is not re-assignable
FacilityLocationEncounterListSpecread · baseencounter: UUID4, start_datetime, end_datetime, status: str; id = external_id. Base of ...ListSpecWithLocation; no endpoint uses it directly
FacilityLocationEncounterListSpecWithLocationread · nested (encounter location_history)Extends list; adds location: dict (serialized via FacilityLocationListSpec)
FacilityLocationEncounterReadSpecread · list & detail (association endpoint)encounter: dict (serialized via EncounterRetrieveSpec), start_datetime, end_datetime, status, created_by/updated_by

Server-maintained behaviour​

  • These are platform-maintained — don't write them from a client: system_availability_status, has_children, has_sub_locations, has_beds, level_cache, parent_cache, cached_parent_json, facility_organization_cache, current_encounter, tags_data, and sort_index (when left unset).
  • On read, parent comes back as the serialized parent chain (get_parent_json()), never the raw FK.
  • Access granted through organizations_add (a new FacilityLocationOrganization row) reaches the location and its descendants in the same request, because cascade_changes() runs synchronously.
  • location_type takes a free Coding (no value-set slug), so it adds coded data without a schema migration. metadata is not exposed through the API.

API integration notes​

  • The model follows the FHIR Location resource, but the payload uses the Django field names on this page (for example, form and location_type).
  • mode separates kind (a location type) from instance (a concrete location such as a bed). Beds are FacilityLocation instances, not a separate model, and instance locations cannot have children.
  • parent, organizations, and mode are settable only at creation (FacilityLocationWriteSpec). Updates go through FacilityLocationUpdateSpec, which omits all three.
  • For fields you can't write, see Server-maintained behaviour.
  • Create checks: the parent must be in the same facility (Parent Incompatible with Location), must not be an instance, and must have level_cache below LOCATION_MAX_DEPTH (default 10). A facility holds at most MAX_LOCATION_IN_FACILITY (default 1000) non-deleted locations.
  • Delete is a soft delete. It fails with Location has active children while the location has non-deleted children.
  • Organizations: GET .../organizations/ lists the linked organizations. POST .../organizations_add/ and POST .../organizations_remove/ take { organization: uuid }. Both need can_update_facility_location_obj on the location and can_manage_facility_organization_obj on an organization of the same facility. Remove hard-deletes the link row, then re-saves the location and runs cascade_changes().
  • Tags: the viewset uses EMRTagMixin with resource_type = location. The create body can carry tags: [{ tag, expiry_offset? }], and POST .../set_tags/ and POST .../remove_tags/ change them later. A tag must have resource location and belong to this facility or to the instance. ?tags=<uuid>,<uuid> with tags_behavior=any (default) or all filters the list. See Tag config.
  • List filters: parent (UUID; an empty ?parent= returns top-level locations), name (contains), mode, form, operational_status, status (case-insensitive exact), available (no current encounter), has_beds, has_sub_locations, and mine (locations linked to the user's organizations). Ordering: sort_index.
  • Encounter occupancy lives at the nested .../location/<location_id>/association/ endpoint (FacilityLocationEncounter). The POST .../associate_encounter/ action on the location is an unfinished stub: it runs permission checks and returns no response.
  • A location can be the subject of a form. A questionnaire with subject_type location takes submissions at POST /api/v1/questionnaire/<questionnaire_id>/submit_resource/, with the location external_id in resource_id. Care stores them as FacilityResourceQuestionnaireResponse rows, listed at GET /api/v1/resource_responses/?subject_type=location&subject_id=<location_id>. Submit needs can_submit_questionnaire, and read needs can_view_resource_responses, in an organization in the location's facility_organization_cache.