Skip to main content
Version: 3.1

Valueset

Technical reference for the ValueSet module in Care EMR. For the plain-language model, see the Valueset concept.

Source:

A valueset stores rules, not a list of codes. The model keeps compose as opaque JSON. The include and exclude clauses, filters, validation and the read and write schemas live in the Pydantic resource specs. Members resolve against the terminology server each time the valueset is searched.

Every valueset has a scope (auth_context): instance, facility, department (facility_organization) or user. The scope decides where the slug must be unique, who can write the valueset and who can read it.

Models​

ModelBasePurpose
ValueSetEMRBaseModelA named composition of codes, with a scope and an optional parent
ValueSetFacilityOrganizationEMRBaseModelLinks a facility-scoped valueset to a department that can read it
UserFacilityValueSetPreferenceEMRBaseModelA user's choice of valueset for a slug in one facility
UserValueSetPreferenceEMRBaseModelA user's favourite (starred) codes in one valueset
RecentViewsManagernoneA Redis helper for a user's recently used codes in one valueset; not a database model

The database models extend EMRBaseModel.

ValueSet fields​

FieldModel typeSpec typeRequired on createDefaultNotes
slugSlugField(255)SlugTypeyes—5 to 50 characters; see Slug rules
nameCharField(255)stryes—The create and update specs accept a blank name; only ValueSetSpec rejects it
descriptionTextFieldstryes""The field must be sent; an empty string is accepted
composeJSONFieldValueSetComposeyesdictInclude and exclude clauses; see compose shape
statusCharField(255)ValueSetStatusOptionsyes—See status values
disable_compositionBooleanFieldboolyesFalseWhen true, the parent's clauses are not used
auth_contextCharField(255)ValueSetAuthContextyes"instance"The scope. Create spec only; not in the update or read specs
facilityFK facility.Facility, nullable, CASCADEUUID4 | Nonefor facility and user scopeNoneFor facility_organization scope, copied from the department. Create spec only
facility_organizationFK emr.FacilityOrganization, nullable, CASCADEUUID4 | Nonefor facility_organization scopeNoneCreate spec only
parentFK self, nullable, CASCADEUUID4 | Nonewhen inherited is trueNoneMust be an instance valueset, or a facility or department valueset of the same facility. Create spec only
inheritedBooleanFieldboolyesFalseA facility customization. Takes the parent's slug on create and keeps its slug on update. Create spec only
is_system_definedBooleanFieldbool (read spec only)—FalseSet only by sync_valueset; no write spec declares it
internal_organization_cacheArrayField(IntegerField)——listDepartment IDs that grant read access: the linked departments and their parent departments

ValueSetAuthContext values​

ValueTarget storedCreate and updateReadScreen
instance—No role permission grants it. The API refuses it with You are not authorized to create a value setEvery signed-in userShared catalogue in facility settings, read only
facilityfacility"Can Create/Update ValueSets" in the facility's root organization"Can Read ValueSets" in a linked department or a parent department of oneFacility settings > Forms > ValueSets, This facility tab
facility_organizationfacility_organization and facility"Can Create/Update ValueSets" in that department or a parent department"Can Read ValueSets" in that department or a parent departmentNone
userfacility"Can Create/Update ValueSets" in any organization of the facility. Update and delete: the creator onlyThe creator onlyNone

A facility valueset with no linked department is visible to no facility user, its creator included. A role in the root organization does not make it visible, unless the valueset is shared with the root organization (Administration).

Slug rules​

RuleWhereBehaviour
FormatSlugType5 to 50 characters: letters, digits, - and _, starting and ending with a letter or digit
Unique per scopeDatabase constraintsAmong rows with deleted=False: instance-wide for instance, per facility for facility, per department for facility_organization, per user and facility for user
Constraint namesDatabaseunique_valueset_slug_instance, unique_valueset_slug_facility, unique_valueset_slug_facility_organization, unique_valueset_slug_user
Reserved prefix on createValueSetCreateSpecA slug that contains system- is refused unless inherited is true: Cannot create valueset with system like slug
Reserved prefix on updateValueSetUpdateSpecThe same check, skipped when the stored valueset is system-defined or inherited
InheritedCreate and updateAn inherited valueset takes its parent's slug on create, and keeps its stored slug on update

Create and update do not check slug uniqueness in the spec. A duplicate reaches the database constraint and fails with HTTP 500 (IntegrityError), not a validation error.

ValueSetStatusOptions values​

ValueBehaviour
draftNot used for slug resolution
activeThe only status used for slug resolution
retiredNot used for slug resolution. expand by ID still searches it
unknownNot used for slug resolution

compose shape​

compose holds a ValueSetCompose (care.emr.resources.common.valueset). Every nested model sets extra="forbid", so unknown keys are rejected.

ValueSetCompose​

FieldTypeRequiredDefault
idstr | NonenoNone
includelist[ValueSetInclude]yes (the list can be empty)—
excludelist[ValueSetInclude] | NonenoNone
propertylist[str] | NonenoNone

ValueSetInclude (used for include and exclude)​

FieldTypeRequiredDefault
idstr | NonenoNone
systemstr | NonenoNone
versionstr | NonenoNone
conceptlist[ValueSetConcept] | NonenoNone
filterlist[ValueSetFilter] | NonenoNone

A clause can set concept or filter, not both: Only one of 'concept' or 'filter' can be present, not both.

ValueSetConcept​

FieldTypeRequiredDefault
idstr | NonenoNone
codestr | NonenoNone
displaystr | NonenoNone

ValueSetFilter​

FieldTypeRequiredDefault
idstr | NonenoNone
propertystr | NonenoNone
opstr | NonenoNone
valuestr | NonenoNone

op must be one of =, is-a, descendent-of, is-not-a, regex, in, not-in, generalizes, child-of, descendent-leaf, exists. Any other value fails with Invalid op value ....

The same file also defines a plain ValueSet model (name, optional status, compose) next to these classes.

ValueSetFacilityOrganization​

FieldType
valuesetFK ValueSet, CASCADE
organizationFK FacilityOrganization, CASCADE

Only set_facility_organizations writes these rows. It replaces every row of the valueset, then calls sync_facility_org_cache().

UserFacilityValueSetPreference​

FieldType
userFK users.User, CASCADE
slugSlugField(255)
facilityFK facility.Facility, CASCADE
valuesetFK emr.ValueSet, CASCADE

One row per user, facility and slug (constraint on non-deleted rows). set_slug_preference creates it or points it at the new valueset.

UserValueSetPreference​

FieldType
userFK users.User, CASCADE
valuesetFK emr.ValueSet, CASCADE
favorite_codesJSONField, default list

unique_together = ("user", "valueset"). The class constant MAX_FAVORITES (default 50, setting MAX_FAVORITES_FOR_VALUESET) is defined but nothing reads it, so add_favourite has no limit.

RecentViewsManager​

A class-method helper, not a database model. It keeps a user's recent codes for one valueset in a Redis list.

MemberBehaviour
get_client()Opens the "default" Redis connection on first use
get_recent_views(cache_key)Returns every entry, decoded from JSON
add_recent_view(cache_key, code_obj)Does nothing without a code. Removes an entry with the same code, pushes the new entry first, then trims the list to MAX_RECENT_VIEW
remove_recent_view(cache_key, code_obj)Removes entries with the same code; does nothing without a code
clear_recent_views(cache_key)Deletes the list
_remove_by_code(cache_key, code)Internal. Removes matching entries and skips entries that are not valid JSON

MAX_RECENT_VIEW defaults to 20 (setting MAX_RECENT_VIEW_FOR_VALUESET).

Resource specs (API schema)​

Every spec extends EMRResource (resources/base.py). Serialization copies only the fields that the read spec declares.

SpecRoleFields
ValueSetBaseSpecShared base (__model__ = ValueSet)id (UUID4, default None), slug, name, description, compose, status, disable_composition
ValueSetCreateSpecWrite · createBase, plus auth_context, facility, facility_organization, inherited, parent
ValueSetUpdateSpecWrite · updateBase fields only
ValueSetMinimalReadSpecReadBase, plus is_system_defined
ValueSetReadSpecRead · list and detailMinimal read, plus created_by and updated_by
ValueSetSpecBody of preview_searchBase, plus the name and slug validators

The read specs do not return auth_context, facility, facility_organization, parent or inherited.

Validation​

RuleSpecBehaviour
Scope targetValueSetCreateSpecFacility is required for facility and user; Facility organization is required for facility_organization
InheritanceValueSetCreateSpecParent is required for inherited value sets
Parent existsValueSetCreateSpecParent not found when no valueset has that ID
Parent scopeValueSetCreateSpecParent not found unless the parent is an instance valueset, or a facility or department valueset of the same facility
Facility and department existValueSetCreateSpecFacility not found, Facility organization not found
Reserved slugCreate and update specsSee Slug rules
Name not blankValueSetSpec onlyName cannot be empty; strips surrounding whitespace
Slug uniqueValueSetSpec onlySlug must be unique when a valueset of any scope uses the slug
op allowlistValueSetFilterSee compose shape
concept or filterValueSetIncludeBoth present fails

Server-side serialization hooks​

HookSpecEffect
perform_extra_deserializationValueSetCreateSpecLooks up the facility for facility and user scope. For facility_organization, sets the department, its facility and the access cache. Resolves and checks the parent, and copies the parent's slug when inherited is true
perform_extra_deserializationValueSetSpecStores compose dumped with exclude_defaults=True, exclude_none=True
perform_extra_serializationBoth read specsSets id to external_id; ValueSetReadSpec also fills created_by and updated_by

ValueSetCreateSpec does not re-dump compose, and ValueSetUpdateSpec has no deserialization hook.

Methods & save behaviour​

ValueSet does not override save() or delete(). Its methods resolve codes:

  • create_composition(systems=None) groups the include and exclude clauses by terminology system, dumping each clause with exclude_defaults=True. Unless disable_composition is true, it then adds the parent's clauses to the same lists, recursively.
  • search(search="", count=10, display_language=None) runs one terminology query per terminology system and joins the results.
  • lookup(code) returns true when the code matches in any terminology system.
  • sync_facility_org_cache() sets internal_organization_cache to the linked departments and all their parent departments.

Codes resolve at request time. Changing compose changes the members at once, and there is no expansion to rebuild.

The viewset's perform_update keeps the stored slug of an inherited valueset, whatever slug the request sends.

Delete is a soft delete: it sets deleted=True.

API integration notes​

  • The API is served at /api/v1/valueset/. A valueset is looked up by its external ID (UUID); before 3.1 the lookup used the slug.
  • The viewset extends EMRModelViewSet: create (POST), retrieve and list (GET), update (PUT, and PATCH as partial update), destroy (DELETE) and the generic upsert (POST).
  • The list accepts name (contains, case-insensitive), status (exact, case-insensitive), auth_context and facility (facility external ID).
  • The permission class needs only a signed-in user. The viewset has no permissions_controller.
  • List, retrieve and the detail actions that call get_object() use the visible queryset, so a valueset that the user cannot read returns 404.
  • Refused updates and deletes return the message You are not authorized to create a value set. The exception is a personal (user) valueset updated or deleted by someone other than its creator: Only the creator of the value set can update it.

Authorization​

Actioninstancefacilityfacility_organizationuser
CreateNo role permission grants it"Can Create/Update ValueSets" in the facility root"Can Create/Update ValueSets" in the department or a parent"Can Create/Update ValueSets" in any organization of the facility
Update, deleteNo role permission grants itAs createAs createAs create, and only the creator
List, retrieveEvery signed-in user"Can Read ValueSets" in a linked department or a parent of one"Can Read ValueSets" in the department or a parentThe creator only

A write role in another facility's root, a write role in a department, or a read-only role in the root does not allow creating a facility valueset.

PermissionDisplay nameDefault facility roles
can_write_valuesetCan Create/Update ValueSetsFacility Admin
can_read_valuesetCan Read ValueSetsFacility Admin, Administrator, Doctor, Nurse, Staff, Pharmacist, Volunteer

The role lists are defaults. Roles can be created and edited, and system roles are rewritten from code on each sync.

Endpoints​

ActionMethodLevelBehaviour
get_facility_organizationsGETdetailLists the linked departments. facility scope only, otherwise 403 Facility organizations can only be set for facility level questionnaires. Needs the update permission
set_facility_organizationsPOSTdetailBody facility_organizations: list[UUID4]. Replaces the linked departments; each must belong to the valueset's facility. Refreshes the access cache. Same scope and permission checks as above
set_slug_preferencePOSTdetailBody slug, facility. Saves this valueset as the user's choice for the slug in that facility. The user must be able to read the valueset; no write permission is needed. A valueset of another facility fails with Cannot set preference for different facility's valueset
expandPOSTdetailSearches this valueset. Does not check status
expand_slugPOSTlistResolves the slug (see below), searches that valueset, and returns it with the results
preview_searchPOSTlistBody is a ValueSetSpec; search and count come from the query string. Builds an unsaved valueset and searches it. A parent's clauses are not included. Needs only sign-in
validate_codePOSTdetailBody is a Coding. Returns result true or false
lookup_codePOSTlistLooks up a code and system in the terminology server. Not found returns 404 No results found for the given system and code. Needs only sign-in
favouritesGETdetailThe user's favourite codes in this valueset
favourites_by_slugGETlistThe user's favourite codes in the valueset that the slug resolves to
add_favouritePOSTdetailAdds a code that belongs to the valueset, otherwise Invalid code value. Needs no write permission
remove_favouritePOSTdetailRemoves a code from the favourites
clear_favouritesPOSTdetailEmpties the favourites
add_recent_viewPOSTdetailAdds a code that belongs to the valueset to the recent codes, otherwise Invalid code value
remove_recent_viewPOSTdetailRemoves a code from the recent codes
recent_viewsGETdetailThe user's recent codes in this valueset
recent_views_by_slugGETlistThe user's recent codes in the valueset that the slug resolves to
clear_recent_viewsPOSTdetailDeletes the recent codes

expand and expand_slug take search (default ""), count (default 10, from 1 to 99) and display_language (default en-gb). expand_slug also takes slug and an optional facility.

Favourites are cached under user_valueset_code_prefs:<valueset>:<user>:favourites. Recent codes use the same prefix with :recent_views.

Slug resolution​

get_closest_valueset(queryset, slug, user, facility=None) picks the valueset that a slug means. expand_slug, favourites_by_slug and recent_views_by_slug call it with the visible queryset.

  • Only active valuesets count.
  • With a facility: the user's saved preference for that facility and slug, if it is still visible and active. Otherwise a facility valueset of that facility, then an instance valueset.
  • Without a facility: an instance valueset only.
  • When nothing matches: No valueset found.

System valuesets​

  • System valuesets are defined in code (CareValueset). The sync_valueset command writes them and marks them is_system_defined. It skips an existing one unless --overwrite is given.
  • sync_valueset runs at start-up in the celery scripts.
  • They take the default scope instance, so no role permission allows editing them. A facility can customize one with an inherited facility valueset.
  • Example: "Condition", slug system-condition-code.
  • A coded field bound to a system valueset, such as a condition's code, is checked on save against the first valueset with that slug, whatever its facility. The errors are Valueset does not exist in care, Resync valuesets and Code does not exist in the valueset.

Favourite and recent codes are per user. They are not part of the valueset definition.