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:
- Model:
care/emr/models/location.py - Resource spec:
care/emr/resources/location/spec.py - Viewset:
care/emr/api/viewsets/location.py - Base resource:
care/emr/resources/base.py - Coding type:
care/emr/resources/common/coding.py
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
| Model | Purpose |
|---|---|
FacilityLocation | A node in a facility's location tree (building, ward, room, bed, …) |
FacilityLocationOrganization | Grants a FacilityOrganization access to a location |
FacilityLocationEncounter | Records 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
| Field | Type | Spec values / shape | Notes |
|---|---|---|---|
name | CharField(255) | str, required | Not unique. The model has a sibling-uniqueness helper, but the API does not call it (see validate_uniqueness()) |
description | CharField(255) | str, required | Free-text |
status | CharField(255) | StatusChoices enum | One of StatusChoices |
operational_status | CharField(255) | FacilityLocationOperationalStatusChoices enum | FHIR operational status code; one of FacilityLocationOperationalStatusChoices |
system_availability_status | CharField(255) | str (read-only) | Server-maintained, derived from encounter association. Resolves to one of LocationAvailabilityStatusChoices (available / reserved) |
mode | CharField(255) | FacilityLocationModeChoices enum | kind (a type, e.g. a building/ward) or instance (a single location, e.g. Bed 1). Set on create, then frozen. See FacilityLocationModeChoices |
location_type | JSONField (default=dict, nullable) | Coding | None (default None) | A single FHIR Coding, not a CodeableConcept. Unbound — any coding is accepted |
form | CharField(255) | FacilityLocationFormChoices enum | FHIR physical form; one of FacilityLocationFormChoices |
inventory_usage | CharField(255) (default="none") | InventoryUsage enum, default none | How 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.
| Field | Type | Notes |
|---|---|---|
parent | FK → FacilityLocation | SET_NULL, nullable. Immediate parent. Accepted on write as a UUID (parent); on read it's dropped in favour of the serialized parent JSON |
root_location | FK → self | CASCADE, related_name="root", nullable. Top of this node's tree. Excluded from specs |
has_children | BooleanField | default=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_locations | BooleanField | default=False. True when the node has a non-deleted child in kind mode. Recomputed by sync_children_flags(). Read-only; filterable |
has_beds | BooleanField | default=False. True when the node has a non-deleted child in instance mode. Recomputed by sync_children_flags(). Read-only; filterable |
level_cache | IntegerField | default=0. Depth in the tree (parent.level_cache + 1) |
parent_cache | ArrayField[int] | Ordered ancestor IDs (parent.parent_cache + [parent.id]) |
cached_parent_json | JSONField (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_index | IntegerField | default=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
| Field | Type | Notes |
|---|---|---|
facility | FK → facility.Facility | PROTECT. Owning facility. Excluded from specs — resolved from route/context |
facility_organization_cache | ArrayField[int] | default=list. Org IDs that can reach this location; rebuilt by sync_organization_cache() |
current_encounter | FK → Encounter | SET_NULL, nullable, default=None. Populated from FacilityLocationEncounter. Excluded from the base spec; surfaced as serialized JSON in list/retrieve specs |
metadata | JSONField | default=dict. Open bag for deployment-specific data. Not in any spec, so the API neither reads nor writes it |
Tags
| Field | Type | Notes |
|---|---|---|
tags | ArrayField[int] | default=list. Tag config IDs applied to the location. Rendered as tag objects in FacilityLocationListSpec through SingleFacilityTagManager().render_tags() |
tags_data | JSONField | default=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
| Value | Meaning |
|---|---|
active | Location is active |
inactive | Location is inactive |
unknown | Status unknown |
FacilityLocationOperationalStatusChoices values
FHIR HL7 v2 bed/location operational status codes.
| Code | Meaning |
|---|---|
C | Closed |
H | Housekeeping |
O | Occupied |
U | Unoccupied |
K | Contaminated |
I | Isolated |
FacilityLocationModeChoices values
| Value | Meaning |
|---|---|
instance | A single, concrete location (e.g. Bed 1). Instances cannot have children |
kind | A class/type of location (e.g. a ward or building) |
FacilityLocationFormChoices values
FHIR location-physical-type codes.
| Code | Meaning |
|---|---|
si | Site |
bu | Building |
wi | Wing |
wa | Ward |
lvl | Level |
co | Corridor |
ro | Room |
bd | Bed |
ve | Vehicle |
ho | House |
ca | Cabinet |
rd | Road |
area | Area |
jdn | Jurisdiction |
vi | Virtual |
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.
| Value | Meaning |
|---|---|
planned | Occupancy planned |
active | Currently occupied |
reserved | Reserved |
completed | Occupancy ended |
LocationAvailabilityStatusChoices values
The server-derived values that system_availability_status resolves to.
| Value | Meaning |
|---|---|
available | Not actively tied to an encounter |
reserved | Tied 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
}
Related models
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.
| Field | Type | Spec | Notes |
|---|---|---|---|
status | CharField(25) | LocationEncounterAvailabilityStatusChoices | One of planned / active / reserved / completed |
location | FK → FacilityLocation | excluded / nested | CASCADE. Surfaced as JSON in ...ListSpecWithLocation |
encounter | FK → Encounter | UUID on write, JSON on read | CASCADE. Validated to exist on create |
start_datetime | DateTimeField | datetime (required) | Occupancy start |
end_datetime | DateTimeField (nullable) | datetime | None | Occupancy 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
activerow,current_encounteris that encounter,system_availability_statusisreserved, and the encounter'scurrent_locationis this location. - If not,
current_encounterisnullandsystem_availability_statusisavailable. - Any other encounter whose
current_locationis this location loses it.
The viewset (_validate_data) enforces these rules:
- A
kindlocation cannot take encounters (Cannot assign encounters to location kind). end_datetimemust not be beforestart_datetime. Acompletedrow requiresend_datetime. For anactiverow, the checks ignoreend_datetime.- A row must not conflict with another
activeorplannedrow on the same location (Conflict in schedule). - A location has at most one
activerow, and an encounter has at most oneactivelocation. - A
completedrow 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():
- A save with an empty
update_fieldslist returns without a write. - When
parentis set, the parent row is locked (select_for_update). - On insert with a
parent,level_cache,root_location, andparent_cacheare derived from the parent. - On update,
cached_parent_jsonis cleared so it rebuilds lazily. Ifupdate_fieldsis given,cached_parent_jsonis added to it. - On any save, a
sort_indexof0ornullbecomesmax(sibling sort_index) + 1. - After
super().save(),sync_organization_cache()persistsfacility_organization_cachethrough a secondsave(update_fields=[...]), so each write touches the row twice. 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 linkedFacilityLocationOrganization, and the facility'sdefault_internal_organization_id, then writesfacility_organization_cache.get_parent_json()— returns the cached parent chain, refreshingcached_parent_json(viaFacilityLocationListSpec.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 setshas_children(any child),has_sub_locations(akindchild), andhas_beds(aninstancechild) with a querysetupdate(), then repeats once for the parent.cascade_changes()/handle_cascade(base_location)—handle_cascadehas the Celery@app.taskdecorator, butcascade_changes()calls it directly, so it runs synchronously in the same request. It walks every descendant and callssave(update_fields=["cached_parent_json"]). Each save clears the node's parent JSON and re-runssync_organization_cache(), so descendants pick up the new organization IDs. It runs when aFacilityLocationOrganizationrow is saved and afterorganizations_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.
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 class | Role | Exposes / notes |
|---|---|---|
FacilityLocationBaseSpec | shared base | __model__ = FacilityLocation; id: UUID4 | None. __exclude__ = [parent, facility, organizations, root_location, current_encounter] |
FacilityLocationSpec | shared fields | status, 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 |
FacilityLocationWriteSpec | write · create | Adds 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 |
FacilityLocationUpdateSpec | write · update | Same fields as FacilityLocationSpec (an empty subclass), so it has no parent/organizations/mode — hierarchy and mode are fixed after creation |
FacilityLocationMinimalListSpec | read · 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() |
FacilityLocationListSpec | read · list | Extends minimal; adds current_encounter: dict | None, serialized via EncounterListSpec when present, and tags: list[dict] (default []), rendered via SingleFacilityTagManager().render_tags(obj) |
FacilityLocationRetrieveSpec | read · detail | Extends list; adds created_by/updated_by (via serialize_audit_users) |
Encounter-association specs
| Spec class | Role | Exposes / notes |
|---|---|---|
FacilityLocationEncounterBaseSpec | shared base | __model__ = FacilityLocationEncounter; id: UUID4 | None. __exclude__ = [encounter, location] |
FacilityLocationEncounterCreateSpec | write · create | status (LocationEncounterAvailabilityStatusChoices), encounter: UUID4, start_datetime, end_datetime: datetime | None. Validator: encounter must exist. perform_extra_deserialization resolves the encounter UUID to an FK |
FacilityLocationEncounterUpdateSpec | write · update | status, start_datetime, end_datetime (no default, so the key is required; null allowed). Encounter is not re-assignable |
FacilityLocationEncounterListSpec | read · base | encounter: UUID4, start_datetime, end_datetime, status: str; id = external_id. Base of ...ListSpecWithLocation; no endpoint uses it directly |
FacilityLocationEncounterListSpecWithLocation | read · nested (encounter location_history) | Extends list; adds location: dict (serialized via FacilityLocationListSpec) |
FacilityLocationEncounterReadSpec | read · 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, andsort_index(when left unset). - On read,
parentcomes back as the serialized parent chain (get_parent_json()), never the raw FK. - Access granted through
organizations_add(a newFacilityLocationOrganizationrow) reaches the location and its descendants in the same request, becausecascade_changes()runs synchronously. location_typetakes a freeCoding(no value-set slug), so it adds coded data without a schema migration.metadatais not exposed through the API.
API integration notes
- The model follows the FHIR
Locationresource, but the payload uses the Django field names on this page (for example,formandlocation_type). modeseparateskind(a location type) frominstance(a concrete location such as a bed). Beds areFacilityLocationinstances, not a separate model, andinstancelocations cannot have children.parent,organizations, andmodeare settable only at creation (FacilityLocationWriteSpec). Updates go throughFacilityLocationUpdateSpec, 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 aninstance, and must havelevel_cachebelowLOCATION_MAX_DEPTH(default 10). A facility holds at mostMAX_LOCATION_IN_FACILITY(default 1000) non-deleted locations. - Delete is a soft delete. It fails with
Location has active childrenwhile the location has non-deleted children. - Organizations:
GET .../organizations/lists the linked organizations.POST .../organizations_add/andPOST .../organizations_remove/take{ organization: uuid }. Both needcan_update_facility_location_objon the location andcan_manage_facility_organization_objon an organization of the same facility. Remove hard-deletes the link row, then re-saves the location and runscascade_changes(). - Tags: the viewset uses
EMRTagMixinwithresource_type = location. The create body can carrytags: [{ tag, expiry_offset? }], andPOST .../set_tags/andPOST .../remove_tags/change them later. A tag must haveresourcelocationand belong to this facility or to the instance.?tags=<uuid>,<uuid>withtags_behavior=any(default) orallfilters 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, andmine(locations linked to the user's organizations). Ordering:sort_index. - Encounter occupancy lives at the nested
.../location/<location_id>/association/endpoint (FacilityLocationEncounter). ThePOST .../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_typelocationtakes submissions atPOST /api/v1/questionnaire/<questionnaire_id>/submit_resource/, with the locationexternal_idinresource_id. Care stores them asFacilityResourceQuestionnaireResponserows, listed atGET /api/v1/resource_responses/?subject_type=location&subject_id=<location_id>. Submit needscan_submit_questionnaire, and read needscan_view_resource_responses, in an organization in the location'sfacility_organization_cache.
Related
- Reference: Facility
- Reference: Organization
- Reference: Encounter
- Reference: Tag config
- Reference: Device
- Reference: Base model
- Concept: Location
- Source: location.py on GitHub
- Source: location/spec.py on GitHub