Skip to main content
Version: 3.1

Specimen Definition

Technical reference for the SpecimenDefinition module in Care EMR. For the plain-language overview, see the Specimen Definition concept.

A SpecimenDefinition is a facility-scoped template for one kind of specimen: the specimen type to collect, the patient preparation, a collection template, and the container and testing detail. An Activity Definition lists specimen definitions of its own facility in specimen_requirements, and a Service Request creates Specimens from specimen definitions of the same facility.

When a specimen is created from a definition, the backend sets status = available, copies type_collected into specimen_type, and links the definition. It does not copy the collection template; the frontend pre-fills method, body_site and quantity from it in the specimen collection form.

The Django model is only the storage layer: type_collected, patient_preparation, collection and type_tested are JSONFields. Their structure, value-set bindings and read/write schemas live in the Pydantic resource specs below.

Source:

Models​

ModelPurpose
SpecimenDefinitionReusable, facility-scoped definition of one kind of specimen: type collected, patient preparation, collection template, and type tested (container and testing detail)

SpecimenDefinition extends SlugBaseModel, which sets FACILITY_SCOPED = True and adds slug helpers. SlugBaseModel builds on EMRBaseModel (history, meta, created_by, updated_by) and BaseModel (external_id, created_date, modified_date, and soft delete through deleted).

SpecimenDefinition fields​

Identity & status​

FieldTypeRequiredNotes
facilityFK → facility.Facility (PROTECT)model: optionalnull=True, blank=True, default=None. Never client-supplied: the ViewSet sets it from the facility in the URL on create. Excluded from every spec (__exclude__ = ["facility"])
versionIntegerFielddefault 1Exposed by SpecimenDefinitionReadSpec only; not accepted on write
slugCharField(255)yes (server-built)Stored as f-<facility_external_id>-<slug_value>. Clients send the bare slug_value
titleCharField(1024)yesHuman-readable name
derived_from_uriTextFieldoptionalnull=True, blank=True
statusCharField(255)yesConstrained by SpecimenDefinitionStatusOptions; see enum
descriptionTextFieldyesFree text

Collection & testing detail (JSON fields)​

The model stores these as raw JSON; the spec defines their shape and value-set bindings. See Nested JSON shapes.

FieldModel typeSpec typeNotes
type_collectedJSONField (null=True, blank=True)Coding bound to Specimen Type CodeRequired on write. See value sets
patient_preparationJSONField (default=list)list[Coding] bound to Prepare Patient Prior Specimen CodeDefaults to []
collectionJSONField (null=True, blank=True)CollectionTemplateSpec, optionalCollection template: procedure code, quantity, method, body site. See CollectionTemplateSpec
type_testedJSONField (default=dict)TypeTestedSpec, optionalContainer and testing detail. See TypeTestedSpec

Each bound coded field takes a Coding (system, version, code, display; other keys are refused). ValueSetBoundCoding checks the code against the bound value set during deserialization and rejects an unknown code with "Code does not exist in the valueset".

Enums​

SpecimenDefinitionStatusOptions values​

ValueDisplay label
draftDraft
activeActive
retiredRetired. The frontend's Delete action sets this status

PreferenceOptions values​

ValueDisplay label
preferredPreferred
alternateAlternate

HandlingConditionOptions values​

Used by HandlingSpec.temperature_qualifier, which the 3.1 form does not expose.

ValueDisplay label
roomnone (API only)
refrigeratednone (API only)
frozennone (API only)

Nested JSON shapes​

The specs below give the JSON fields their structure. All are Pydantic models in spec.py, except Coding.

Shared types​

TypeWhereShape
Codingresources/common/coding.py{ system: str?, version: str?, code: str (required), display: str? }, extra="forbid"
QuantitySpecspec.py{ value: Decimal (max_digits=20, decimal_places=0), unit: Coding }: whole-number values
MinimumVolumeSpecspec.py{ quantity: QuantitySpec?, string: str? }; a validator forbids supplying both
ContainerSpecspec.py{ description: str?, capacity: QuantitySpec?, minimum_volume: MinimumVolumeSpec?, cap: Coding? (bound to Container Cap), preparation: str? }
DurationSpecspec.py{ value: Decimal (max_digits=20, decimal_places=0), unit: Coding }; unit is not restricted
RangeSpecspec.py{ low: QuantitySpec?, high: QuantitySpec? }
HandlingSpecspec.py{ temperature_qualifier: HandlingConditionOptions?, temperature_range: RangeSpec?, max_duration: DurationSpec?, instruction: str? }

CollectionTemplateSpec​

New in 3.1. The structured shape of the collection JSON field: commit 3af5d2804 replaced the single collection Coding with this template. All four parts are optional.

FieldTypeBound value setForm label
codeCodingSpecimen Collection Code (system-specimen_collection_code)Collection
quantityQuantitySpecnoneExpected Quantity
methodCodingCollection Method (system-collection-method-code)Collection Method
body_siteCodingBody Site (system-body-site-observation)Body Site
  • Data migration. Migration 0084_multiple_changes wraps every existing non-empty collection value as {"code": <old coding>}.
  • Frontend limits. The 3.1 form accepts a quantity.value that is a whole number of 1 or more, with a unit of milligram, gram, milliliter, drop or microgram. It sends an empty collection as {}.

TypeTestedSpec​

The structured shape of the type_tested JSON field. A definition holds at most one container.

FieldTypeRequiredNotes
is_derivedboolyesForm label Is Derived; the form starts it as false
preferencePreferenceOptionsyesForm label Preference; the form starts it as preferred. See enum
containerContainerSpecoptionalForm section Container Information: Description, Cap, Capacity, Minimum Volume, Preparation
requirementstroptionalForm label Requirement
retention_timeDurationSpecoptionalForm label Retention time; the form offers the units hours and days
single_usebooloptionalForm label Single Use; the form starts it as false
handlingHandlingSpecoptionalAPI only: the 3.1 form has no handling fields. See API integration notes

How other models point to a specimen definition, and what it points to:

SpecimenDefinition.facility → facility.Facility FK, PROTECT, nullable; set from the URL on create
Specimen.specimen_definition → SpecimenDefinition FK, CASCADE, nullable; set by convert_sd_to_specimen
ActivityDefinition.specimen_requirements → SpecimenDefinition ids integer array, no FK; slugs of same-facility definitions become ids on save

Resource specs (API schema)​

All specs build on EMRResource. __exclude__ = ["facility"] keeps facility out of both directions. The ViewSet uses pydantic_model = SpecimenDefinitionWriteSpec for create and update, and pydantic_read_model = SpecimenDefinitionReadSpec for list and retrieve.

Spec classRoleFields / behaviour
BaseSpecimenDefinitionSpecshared baseid, title, derived_from_uri, status, description, type_collected, patient_preparation, collection, type_tested. Holds the value-set bindings and the nested shapes
SpecimenDefinitionWriteSpecwrite · create & updateBase fields plus slug_value: SlugType. perform_extra_deserialization copies slug_value into obj.slug; the ViewSet then qualifies it. facility, version and the stored slug are never client-supplied
SpecimenDefinitionReadSpecread · list & retrieveBase fields plus version: int?, slug: str, slug_config: dict. perform_extra_serialization sets id = obj.external_id and slug_config = obj.parse_slug(obj.slug), which gives { facility, slug_value }

Nested specs used by the schemas: CollectionTemplateSpec, TypeTestedSpec, ContainerSpec, MinimumVolumeSpec, QuantitySpec, DurationSpec, RangeSpec, HandlingSpec (see Nested JSON shapes).

Validation rules​

  • slug_value (SlugType): string, 5–50 characters, matching ^[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]$.
  • Coded fields type_collected, patient_preparation[*], collection.code, collection.method, collection.body_site and type_tested.container.cap: ValueSetBoundCoding checks each code against its bound value set and rejects unknown codes.
  • MinimumVolumeSpec: quantity and string are mutually exclusive; supplying both raises "Only one of quantity or string should be provided".
  • QuantitySpec and DurationSpec value: Decimal, max_digits=20, decimal_places=0 (whole numbers). This covers collection.quantity, container.capacity, container.minimum_volume.quantity and retention_time. The 3.1 form accepts decimals for capacity, minimum volume and retention time, and rounds them to the accounting precision before sending.
  • Slug uniqueness (ViewSet validate_data): the qualified f-<facility>-<slug_value> must not match any other specimen definition (case-insensitive), else "Specimen Definition with this slug already exists.". On update, the check uses the record's own facility and excludes the record itself.

Bound value sets​

FieldValue setSlugComposition
type_collectedSpecimen Type Codesystem-specimen_type-codeHL7 v2-0487 (version 2.0.0), whole code system
patient_preparation[*]Prepare Patient Prior Specimen Codesystem-prepare_patient_prior_specimen_codeSNOMED CT, is-a 703763000
collection.codeSpecimen Collection Codesystem-specimen_collection_codeSNOMED CT, ten listed concepts: aspiration, biopsy, puncture, excision, scraping, clean-catch urine, timed urine, catheterized urine, coughed sputum, finger-prick sampling
collection.methodCollection Methodsystem-collection-method-codeSNOMED CT, the same ten concepts as Specimen Collection Code
collection.body_siteBody Sitesystem-body-site-observationSNOMED CT: a listed set of concepts plus every concept under 442083009; shared with observation definitions
type_tested.container.capContainer Capsystem-container_cap-codeHL7 container-cap code system

Methods & save behaviour​

SpecimenDefinition overrides no save() or delete() and defines no methods. Slug helpers, audit fields and soft delete come from SlugBaseModel and its bases. The side effects below live in the resource spec and the ViewSet, not the model:

  • Slug qualification (write). Clients send a bare slug_value. SpecimenDefinitionWriteSpec.perform_extra_deserialization sets obj.slug = slug_value; then perform_create and perform_update rewrite it with SpecimenDefinition.calculate_slug_from_facility(facility.external_id, slug) to f-<facility_external_id>-<slug_value>.
  • Facility binding (create). perform_create sets instance.facility from the facility_external_id URL kwarg before saving.
  • Slug decomposition (read). SpecimenDefinitionReadSpec.perform_extra_serialization exposes slug_config = obj.parse_slug(obj.slug), which splits the stored slug into { facility, slug_value }.
  • Specimen creation. convert_sd_to_specimen (specimen.py) builds a Specimen with status="available", specimen_type = definition.type_collected and specimen_definition = <definition>. It does not copy the collection template.

API integration notes​

  • Endpoints are facility-scoped. /api/v1/facility/{facility_external_id}/specimen_definition/ supports list, create, retrieve, update and upsert, with lookup_field = "slug". There is no delete.
  • Read authorization. Every action that reads the queryset (list, retrieve, and update through get_object) calls can_list_facility_specimen_definition for the facility in the URL. It checks can_read_specimen_definition ("Can Read Specimen Definition") in any organization of that facility.
  • Write authorization. Create and update call can_write_facility_specimen_definition for the facility in the URL. It checks can_write_specimen_definition ("Can Create Specimen Definition on Facility") in the facility's root organization only; a role in a sub-organization does not pass. An update therefore needs both permissions. A failed check returns 403 "Access Denied to Specimen Definition".
  • Default roles. can_write_specimen_definition: Facility Admin. can_read_specimen_definition: Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist. Each sync rewrites the system roles from code; custom roles can hold either permission.
  • Facility scope. The queryset is filtered to the facility in the URL.
  • Filtering / ordering. status (iexact) and title (icontains) filters; ordering by created_date or modified_date.
  • Write payload (SpecimenDefinitionWriteSpec): send slug_value, title, status, description, optional derived_from_uri, type_collected and patient_preparation as Coding objects, collection as a CollectionTemplateSpec, and type_tested. Do not send facility, version or the qualified slug.
  • Read payload (SpecimenDefinitionReadSpec): adds id (the external_id), version, the qualified slug and slug_config.
  • Frontend behaviour. The 3.1 frontend calls list, retrieve, create and update only. Its Delete action sends a full update with status set to retired. On save it sends an empty collection as {}, drops empty patient preparation rows and leaves out an empty container.
  • Handling and the form. The 3.1 form has no fields for type_tested.handling. Its schema drops keys it does not know, and it sends type_tested as one object.