Skip to main content
Version: 3.1

Specimen

Technical reference for the Specimen module in Care EMR. For what a specimen is, see the Specimen concept.

A Specimen records material collected from a patient for a service request. You create one through the service request, then update it as the specimen moves through collection, receipt, and processing.

Several of the model's fields (care/emr/models/specimen.py) are opaque JSONFields whose structure lives only in the Pydantic resource specs (care/emr/resources/specimen/). The specs define the enums, nested JSON shapes, value-set bindings, validation, and the read/write schemas, so you need both layers to work with this resource.

Source:

Models​

ModelPurpose
SpecimenA sample collected from a patient to fulfil a service request

Specimen extends EMRBaseModel, the shared Care EMR base providing external_id, audit fields, soft-delete through deleted, and history/meta JSON.

Specimen fields​

Identity & status​

FieldModel typeSpec shape / valuesNotes
accession_identifierCharField(255), db_index=Truestr, default ""Lab accession identifier; indexed for lookup, not unique. Defaults to "", so it is optional on write. On create, a blank value becomes the specimen's external_id. On update, a blank value keeps the stored identifier.
statusCharField(20)SpecimenStatusOptions enumRequired in BaseSpecimenSpec, optional in SpecimenUpdateSpec. create_specimen_from_definition defaults it to available. See status values.
specimen_typeJSONFieldCoding bound to value set system-specimen_type-codeKind of material collected, as a single coding. Required in BaseSpecimenSpec, optional in SpecimenUpdateSpec. create_specimen_from_definition takes it from the definition's type_collected unless the request sends one.
FieldModel typeNotes
facilityFK → FacilityPROTECT, nullable; the facility the specimen belongs to. Set on create from the service request's facility. Excluded from all specs (__exclude__).
patientFK → PatientCASCADE; the patient the specimen was collected from. Set on create from the service request's patient.
encounterFK → EncounterCASCADE, nullable; set on create from the service request's encounter.
service_requestFK → ServiceRequestCASCADE, nullable; the order this specimen fulfills. Set on create to the service request the create action runs on. Authorization checks run against it.
specimen_definitionFK → SpecimenDefinitionCASCADE, nullable; the specimen definition this specimen was created from. Set by create_specimen_from_definition.

Collection & processing​

FieldModel typeSpec shapeNotes
collectionJSONField default=dictCollectionSpec | None, default NoneA single collection event: collector, collected time, quantity, method, body site, fasting. See CollectionSpec.
received_timeDateTimeField, nullablestr | None, default NoneWhen the specimen was received.
conditionJSONField default=listlist[Coding] bound to system-specimen-condition-code, default []Coded conditions of the specimen (HL7 v2-0493).
processingJSONField default=listlist[ProcessingSpec], default []Processing steps applied. See ProcessingSpec.
noteTextField, nullablestr | None, default NoneFree-text annotation.

Enums​

SpecimenStatusOptions values​

The status enum (str). draft is Care's own addition.

ValueMeaning
draftCare-specific. The web frontend creates a specimen as draft before collection.
availableDefault status from convert_sd_to_specimen. The web frontend sets it when the specimen is collected.
unavailableDiscard reason in the web frontend: "The specimen is lost, destroyed, or consumed".
unsatisfactoryDiscard reason in the web frontend: "The specimen is unusable due to quality issues".
entered_in_errorDiscard reason in the web frontend: "The specimen record was created by mistake".

Nested JSON specs​

These define the real structure behind the model's JSONFields.

CollectionSpec​

Shape of the collection JSON field: a single collection event.

FieldTypeRequiredNotes
collectorUUID4 | NoneoptionalExternal ID of the collecting User. Validated to exist (User.objects.filter(external_id=...)), else rejected with "Collector user not found". Serialized output adds collector_object, the resolved UserSpec from cache.
collected_date_timedatetime | NoneoptionalWhen the specimen was collected.
quantityQuantitySpec | NoneoptionalAmount collected. See QuantitySpec.
methodCoding | None bound to system-collection-method-codeoptionalCollection method (SNOMED CT). See collection method values.
body_siteCoding | None bound to system-body-site-observationoptionalAnatomical site collected from.
fasting_status_codeable_conceptCoding | None bound to system-fasting-status-codeoptionalPatient fasting status (HL7 v2-0916).
fasting_status_durationDurationSpec | NoneoptionalFasting duration. See DurationSpec.

ProcessingSpec​

One element of the processing list.

FieldTypeRequiredNotes
descriptionstrrequiredDescription of the processing step.
methodCoding | None bound to system-specimen-processing-method-codeoptionalProcessing method (SNOMED CT, descendants of 9265001).
performerUUID4 | NoneoptionalExternal ID of the performing User. Validated to exist, else rejected with "Performer user not found". Serialized output adds performer_object, the resolved UserSpec from cache.
time_date_timestrrequiredWhen the step was performed.

QuantitySpec​

FieldTypeNotes
valueDecimalmax_digits=20, decimal_places=0, so integer-valued.
unitCodingRequired unit coding.

This is a specimen-local quantity spec, distinct from the shared Quantity common type, which allows decimal_places=6, optional value/unit, plus code/meta.

DurationSpec​

FieldTypeNotes
valueintDuration magnitude.
unitCodingRequired unit coding.

Coding (shared common type)​

Every coded field above uses Coding (extra="forbid"):

FieldTypeRequired
systemstr | Noneoptional
versionstr | Noneoptional
codestrrequired
displaystr | Noneoptional

Bound value sets​

The coded fields in the table below bind to Care value sets through ValueSetBoundCoding[<slug>], which validates the submitted code against the value set at write time.

FieldValue setSlugSource system
specimen_typeSpecimen Type Codesystem-specimen_type-codeHL7 v2-0487
condition[]Specimen Conditionsystem-specimen-condition-codeHL7 v2-0493 (v2.0.0)
collection.methodCollection Methodsystem-collection-method-codeSNOMED CT (enumerated, see below)
collection.body_siteBody Sitesystem-body-site-observation(observation body-site value set)
collection.fasting_status_codeable_conceptFasting Statussystem-fasting-status-codeHL7 v2-0916 (v2.0.0)
processing[].methodSpecimen Processing Methodsystem-specimen-processing-method-codeSNOMED CT (< 9265001)

The Specimen Type Code value set is defined in care/emr/resources/specimen_definition/valueset.py, not in the specimen's own value set file. Body Site is defined in care/emr/resources/observation/valueset.py. The others are in care/emr/resources/specimen/valueset.py.

Collection Method value set​

The system-collection-method-code value set enumerates these SNOMED CT codes:

CodeDisplay
129316008Aspiration - action
129314006Biopsy - action
129300006Puncture - action
129304002Excision - action
129323009Scraping - action
73416001Urine specimen collection, clean catch
225113003Timed urine collection
70777001Urine specimen collection, catheterized
386089008Collection of coughed sputum
278450005Finger-prick sampling

Fasting Status (http://terminology.hl7.org/CodeSystem/v2-0916), Specimen Condition (v2-0493) and Specimen Type (v2-0487) are pulled in by code-system reference rather than a fixed concept list. Specimen Processing Method uses a SNOMED CT filter (< 9265001). Body Site combines a fixed list of SNOMED CT concepts with an is-a 442083009 filter.

Resource specs (API schema)​

BaseSpecimenSpec and its subclasses extend EMRResource (care/emr/resources/base.py), which provides serialize (DB object → pydantic, through get_database_mapping) and de_serialize (pydantic → DB object), plus the perform_extra_serialization / perform_extra_deserialization hooks. __exclude__ = ["facility", "request"] on the base keeps those fields from being copied field-for-field.

Spec classRoleKey fields / behaviour
BaseSpecimenSpecshared base; request body of create_specimen; read spec of a specimen shared in a referralid, accession_identifier, status (required), specimen_type (required), received_time, collection, processing, condition, note. __model__ = Specimen, __exclude__ = ["facility", "request"].
SpecimenCreateSpecdefined, not usedAdds subject_patient: UUID4 (required), subject_encounter: UUID4 (required), request: UUID4 | None. No endpoint uses this spec: both create actions take other specs and copy the links from the service request.
SpecimenUpdateSpecwrite · update; also the specimen part of the create_specimen_from_definition bodyRelaxes status and specimen_type to optional (| None) for partial updates.
SpecimenReadSpecread · embedded: the specimens list of the service request detail response, and the response of both create actionsAdds specimen_definition: dict | None. perform_extra_serialization sets id = external_id and, when present, embeds the linked specimen definition through SpecimenDefinitionReadSpec.serialize(...).to_json().
SpecimenRetrieveSpecread · detail: retrieve, the update response, and the accession identifier lookupExtends SpecimenReadSpec, adds service_request: dict | None; serialization additionally embeds the linked service request through ServiceRequestReadSpec.serialize(...).to_json().

Nested specs (defined in the same module): CollectionSpec, ProcessingSpec, QuantitySpec, DurationSpec. See Nested JSON specs.

Validation & server behaviour​

  • collection.collector and processing[].performer must reference existing users by external_id; serialization then injects the resolved collector_object / performer_object (cached UserSpec).
  • The bound coded fields (ValueSetBoundCoding) are validated against their value sets on write; a code outside the value set is rejected.
  • The read specs embed related resources as nested JSON: the linked specimen definition in SpecimenReadSpec and SpecimenRetrieveSpec, and the linked service request in SpecimenRetrieveSpec only.
  • Care skips fields left at their default when it saves a request, so an empty accession_identifier sent on update keeps the stored identifier.
  • No rule controls status changes: an update can set any status. Neither create nor update checks the service request's status.
  • The specimen specs don't override perform_extra_deserialization, so Care appends no server-side status history on write.

API integration notes​

  • The API sits under a facility: /api/v1/facility/{facility}/specimen/.
  • The viewset (SpecimenViewSet) mixes in retrieve and update only (EMRRetrieveMixin, EMRUpdateMixin), plus the custom action POST retrieve_by_accession_identifier. It has no create, no list and no delete.
  • The viewset sets pydantic_model = BaseSpecimenSpec, pydantic_update_model = SpecimenUpdateSpec, pydantic_read_model = SpecimenReadSpec and pydantic_retrieve_model = SpecimenRetrieveSpec.
  • The viewset has no get_queryset of its own, so it does not filter specimens by the facility in the URL: it uses the base queryset of all specimens.
  • The custom action POST retrieve_by_accession_identifier looks up a specimen by accession_identifier, which must be at least 5 characters ("Accession identifier must be at least 5 characters long").
  • The lookup matches the identifier exactly among all specimens, not only those of the facility in the URL. It returns a SpecimenRetrieveSpec.
  • Because accession_identifier is not unique, the lookup can find more than one specimen. It then fails with "Multiple specimens found with the same accession identifier".
  • When no specimen matches, the lookup answers 404. The message "Specimen not found with the given accession identifier" in the code is never sent.
  • The service request detail response embeds every specimen of the request, in any status, as SpecimenReadSpec.

Creation through the service request​

  • The specimen API has no create. Specimens are created through two detail POST actions on the service request: create_specimen and create_specimen_from_definition.
  • create_specimen takes a BaseSpecimenSpec body. create_specimen_from_definition takes specimen_definition (UUID) and specimen (a SpecimenUpdateSpec).
  • The web frontend calls only create_specimen_from_definition. Its create_specimen call is commented out.
  • Care finds the service request among the service requests of the facility in the URL.
  • Both actions check can_write_specimen on the service request. Without it they answer 403 "You do not have permission to create a specimen for this encounter".
  • create_specimen_from_definition looks up the specimen definition by external_id in the facility in the URL. A definition of another facility gives 404.
  • convert_sd_to_specimen builds the new specimen: it links the specimen definition, sets specimen_type to the definition's type_collected, and sets status to available.
  • A status or specimen_type sent in the request's specimen overrides these values. The web frontend sends status draft and the definition's type_collected.
  • Both actions copy patient, encounter and facility from the service request and link the specimen to the service request.
  • If accession_identifier is blank, Care sets it to the specimen's external_id.
  • Both actions return a SpecimenReadSpec.
  • Neither action checks the service request's status. Service request update, by contrast, refuses a completed or cancelled request.

Authorization​

Authorization keys off the linked service_request. One service request may own many specimens.

ActionCheckPermissionRefusal
retrievecan_read_specimen on the specimen's service request"Can Read Specimen" (can_read_specimen)403 "You do not have permission to read this specimen"
updatecan_write_specimen on the specimen's service request"Can Create Specimen on Facility" (can_write_specimen)403 "You do not have permission to write this specimen"
retrieve_by_accession_identifiercan_read_specimen on the matched specimen's service request, after the match"Can Read Specimen" (can_read_specimen)403 "You do not have permission to read this specimen"
create_specimen, create_specimen_from_definitioncan_write_specimen on the service request"Can Create Specimen on Facility" (can_write_specimen)403 "You do not have permission to create a specimen for this encounter"
  • Both checks use the service-request rule. The user must hold the permission in the encounter's departments, or in a department of one of the request's locations.
  • The encounter's departments are the departments added to the encounter with their parents, the departments of the encounter's current location, and the facility's Administration department.
  • A location's departments are the departments linked to the location with their parents, the departments of its parent location, and the facility's Administration department.
  • The user passes when they hold, in one of those departments, a role that carries the permission. A superuser always passes.
  • By default, Facility Admin, Doctor and Nurse hold "Can Create Specimen on Facility". Facility Admin, Administrator, Staff, Doctor, Nurse and Pharmacist hold "Can Read Specimen".
  • Opening a service request checks only can_read_service_request. The specimens embedded in that response are not checked against "Can Read Specimen".
  • Attaching a specimen to a referral checks can_read_specimen on the specimen's service request. A user who opens the shared specimen in the referral needs access to the referral only.
FieldTargetOn deleteSet on create
facilityFacility, nullablePROTECTFrom the service request; excluded from specs
patientPatientCASCADEFrom the service request
encounterEncounter, nullableCASCADEFrom the service request
service_requestServiceRequest, nullableCASCADEThe service request the create action runs on
specimen_definitionSpecimenDefinition, nullableCASCADEThe definition used by create_specimen_from_definition

A Specimen is created through a ServiceRequest and may be created from a SpecimenDefinition. A DiagnosticReport has no link to a specimen: a specimen and a report meet only through their shared service request.