Skip to main content
Version: 3.1

Questionnaire

Technical reference for the Questionnaire module in Care EMR. For what a questionnaire is in the product, see the Questionnaire concept.

Source (model): care/emr/models/questionnaire.py

Source (specs): resources/questionnaire/spec.py · resources/questionnaire/utils.py · resources/questionnaire/questionnaire_organization.py · resources/questionnaire_response/spec.py · resources/form_submission/spec.py

Source (API): api/viewsets/questionnaire/questionnaire.py · security/authorization/questionnaire.py

The Django model is only the storage layer. questions is an opaque JSONField there; the Pydantic specs define its recursive Question shape, the enums, the validation, and the split between the create, update, and read contracts.

A questionnaire has a scope (auth_context) and a revision chain. Each update that changes the questions copies the old row as a past revision, so a response can be read against the questions it was answered with.

Models​

ModelPurpose
QuestionnaireA form definition: questions, subject type, status, scope, and revision chain
FormSubmissionA submission record for a questionnaire, a patient, and an optional encounter, with a status and a response dump
QuestionnaireResponseThe stored answers for a subject, with the questionnaire revision they were answered with
QuestionnaireOrganizationLinks an instance questionnaire to an instance Organization
QuestionnaireFacilityOrganizationLinks a facility questionnaire to a FacilityOrganization (department)
QuestionnaireResponseTemplateA reusable template of answers (template_data) for a questionnaire; see the Questionnaire Response Template reference

All six extend EMRBaseModel.

Questionnaire fields​

Definition​

FieldTypeReqNotes
versionCharField(255)noThe write spec defaults it to "1.0" and freezes it there. It is not the revision number; see internal_revision
slugCharField(255)noDefaults to a generated uuid4. When given, the write spec validates SlugType: 5–50 characters of letters, digits, _ and -, starting and ending with a letter or digit. It may not shadow an internal questionnaire type. Unique per scope; see Slug uniqueness
titleCharField(255)yesStored stripped; a blank or whitespace-only title is rejected
descriptionTextFieldnoDefaults to ""
subject_typeCharField(255)yesSubjectType enum. Set on create only
statusCharField(255)yesQuestionnaireStatus enum
styling_metadataJSONFieldnoDefaults to {}. Not validated
questionsJSONFieldyesDefaults to {} in the database; the API takes a list[Question] tree. See Question nested shape
actionsJSONFieldnoDefaults to []. On create and update, each action's instructions must be authorized for the caller

Scope and revision​

FieldTypeReqNotes
auth_contextCharField(255)yes on createQuestionnaireAuthContext enum. The model default is "instance"; the create spec requires it
facilityFK facility.Facility (CASCADE, nullable)scope-dependentRequired for facility and user scopes. For facility_organization scope, Care copies the organization's facility
facility_organizationFK emr.FacilityOrganization (CASCADE, nullable)scope-dependentRequired for facility_organization scope
internal_revisionIntegerField—Default 1. Server-maintained: incremented when an update changes the questions
latest_revisionFK self (CASCADE, nullable)—null on the current row. On a past revision, points to the current row
questions_hashCharField(255)—SHA-256 of the questions serialized as JSON with sorted keys. Set on create, compared on update

Access caches​

FieldTypeReqNotes
organization_cacheArrayField[int]—Instance Organization ids. Server-maintained; see Access cache sync
internal_organization_cacheArrayField[int]—FacilityOrganization ids. Server-maintained; see Access cache sync

Slug uniqueness​

Slugs are unique per scope among current rows (rows with no latest_revision), compared case-insensitively. The viewset checks this before it saves and raises "Questionnaire with this slug already exists."; four partial unique constraints enforce it in the database for rows that are not deleted and have no latest_revision. The check runs only when a slug is given.

ScopeUnique withinConstraint
instanceAll instance questionnairesunique_questionnaire_slug_instance
facilityThe facilityunique_questionnaire_slug_facility
facility_organizationThe facility organizationunique_questionnaire_slug_facility_organization
userThe facility and the creatorunique_questionnaire_slug_user

Past revisions keep the slug of the row they were copied from.

Enum values​

QuestionnaireAuthContext values​

ValueMeaning
instanceShared across the Care instance. No facility permission allows creating, updating, or deleting it
facilityBelongs to one facility; managed under the facility's settings
facility_organizationBelongs to one facility organization. The frontend has no screen for this scope
userBelongs to its creator within a facility. The frontend has no screen for this scope

QuestionnaireStatus values​

ValueMeaning
activeCan be submitted
retiredCannot be submitted
draftCannot be submitted

The spec has no transition rules, and status does not limit updates or deletes: any status can follow any other.

SubjectType values​

What the questionnaire is about. It is set on create only.

ValueNotes
patientInstance scope only. Submitted through submit without an encounter
encounterSubmitted through submit with an encounter. For a questionnaire that has a facility, the encounter must be in that facility
referralRefused by submit, submit_resource, and form submissions; submitted through a referral
locationSubmitted through submit_resource
deviceSubmitted through submit_resource
facilitySubmitted through submit_resource

QuestionType values​

The type of each question (Question.type). The commented-out members open_choice, attachment, and reference are not implemented.

ValueNotes
groupContainer; must have at least one sub-question
booleanOn submit, the value must be true, false, 1, or 0
decimalOn submit, the value must parse as a decimal
integerOn submit, the value must parse as an integer
string
textOn submit, length capped by settings.MAX_QUESTIONNAIRE_TEXT_RESPONSE_SIZE
displayDisplay only; collects no answer
dateOn submit, an ISO date
dateTimeOn submit, an ISO date-time that includes a timezone
timeOn submit, %H:%M:%S
choiceRequires answer_option or answer_value_set. On submit, the value must be one of the options, or a coding in the value set
urlOn submit, the value needs a scheme and a host
quantityRequires answer_option or answer_value_set. On submit, each answer needs a unit
structuredSkipped by answer validation

EnableOperator values​

The comparison for an enable_when condition (EnableWhen.operator).

Value
exists
equals
not_equals
greater
less
greater_or_equals
less_or_equals

EnableBehavior values​

How several enable_when conditions combine (Question.enable_behavior).

ValueMeaning
allEnabled only if every condition passes. Used when the field is absent
anyEnabled if any condition passes

DisabledDisplay values​

Values for Question.disabled_display.

Value
hidden
protected

AnswerConstraint values​

Values for Question.answer_constraint.

Value
required
optional

QuestionnaireResponseStatusChoices values​

QuestionnaireResponse.status (model default "completed").

Value
completed
entered_in_error

FormSubmissionStatusChoices values​

FormSubmission.status.

Value
draft
submitted
entered_in_error

Question nested shape​

Questionnaire.questions is an opaque JSONField, but the API contract is a recursive list of Question. Fields, with their types and validation:

FieldTypeReqDefaultNotes
link_idstryes—Human-readable link ID; unique across the whole tree
idUUID4 | UUID5yes—Machine ID supplied by the client; unique across the whole tree
codeCoding bound to value set system-observationnoNone
collect_timeboolnofalseCollect a timestamp
collect_performerboolnofalseCollect a performer
textstryes—Question text
descriptionstr | NonenoNone
typeQuestionTypeyes—See values
structured_typestr | NonenoNone
enable_whenlist[EnableWhen] | NonenoNoneConditional display rules
enable_behaviorEnableBehavior | NonenoNone
disabled_displayDisabledDisplay | NonenoNone
collect_body_sitebool | NonenoNone
collect_methodbool | NonenoNone
requiredbool | NonenoNone
repeatsbool | NonenoNone
read_onlybool | NonenoNone
max_lengthint | NonenoNone
answer_constraintAnswerConstraint | NonenoNone
answer_optionlist[AnswerOption] | NonenoNoneInline choices
answer_value_setValueSetConfig | NonenoNone{ slug, external_id }, one required. An external_id may name any value set; a slug alone must name an instance value set ("Value set not found")
is_observationbool | NonenoNone
unitCoding bound to value set system-ucum-unitsnoNone
questionslist[Question]no[]Recursive children
formulastr | NonenoNone
styling_metadatadictno{}
templateslist[TemplateConfig]no[]
is_componentboolnofalse

Validation on each Question:

  • choice and quantity questions must have answer_option or answer_value_set.
  • group questions must have at least one sub-question.
  • answer_value_set must resolve to an existing value set, by external_id or by instance slug.

The write spec also requires every link_id and every id to be unique across the whole tree ("Link IDs must be unique", "Question IDs must be unique").

Sub-specs of Question​

SpecShape
EnableWhen{ question: str (link_id), operator: EnableOperator, answer: Any }
AnswerOption{ value: Any (stripped, non-blank), initial_selected: bool = false }
ValueSetConfig{ slug: SlugType | None, external_id: UUID4 | None }, at least one required
Performer{ performer_type: str, performer_id: str | None, text: str | None }
TemplateConfig{ name: str, content: str, structured_content: dict | None, meta: dict | None }

Resource specs (API schema)​

The resource specs build on EMRResource; the submit request schemas and ValueSetConfig are plain Pydantic models.

Questionnaire​

SpecRoleKey fields / behaviour
QuestionnaireBaseSpecshared__model__ = Questionnaire
QuestionnaireWriteSpecwrite (base)version (frozen "1.0"), slug (optional SlugType), title, description, status, styling_metadata, questions, actions (optional). Validates that the slug does not shadow an internal questionnaire type, a non-empty title, and unique link_ids and ids
QuestionnaireCreateSpecwrite · createAdds auth_context (required), facility, facility_organization, and subject_type. Patient questionnaires only at instance scope; facility required for facility and user scopes; facility_organization required for its scope. Stores questions_hash. There is no organizations field
QuestionnaireUpdateSpecwrite · updateThe write spec fields only: no subject_type, auth_context, facility, or facility_organization. Creates a past revision when the questions change
QuestionnaireReadSpecread · list / detailid (= external_id), slug, version, title, description, status, subject_type, styling_metadata, questions (raw list), created_by, updated_by, internal_revision, actions. It does not return auth_context, facility, or facility_organization
QuestionnaireSpecunusedAn empty subclass of the write spec; no viewset uses it

Value sets bound on questions: code → system-observation, unit → system-ucum-units. answer_value_set references a ValueSet by external_id, or an instance value set by slug.

Questionnaire response​

SpecRoleKey fields / behaviour
EMRQuestionnaireResponseBaseshared__model__ = QuestionnaireResponse
QuestionnaireResponseUpdatewrite · updatestatus: QuestionnaireResponseStatusChoices (default completed)
QuestionnaireResponseReadSpecread · detailid, status, questionnaire (the revision the response was answered with), questionnaire_latest_revision_id (the current questionnaire), subject_id, responses, cleaned_response, encounter (external id or None), structured_responses, structured_response_type, created_by, updated_by, created_date, modified_date

Submit request schema​

POST /api/v1/questionnaire/<id>/submit/ takes a plain Pydantic request, and POST /api/v1/questionnaire/<id>/submit_resource/ takes the resource variant.

SpecShape
QuestionnaireSubmitRequest{ results: list[QuestionnaireSubmitResult], resource_id: UUID4, encounter: UUID4 | None, patient: UUID4, form_submission: UUID4 | None }
QuestionnaireSubmitResult{ question_id: UUID4 | UUID5, body_site: Coding | None, method: Coding | None, taken_at: datetime | None, values: list[QuestionnaireSubmitResultValue], note: str | None, sub_results: list[list[QuestionnaireSubmitResult]] }
QuestionnaireSubmitResultValue{ value: str | None, unit: Coding | None, coding: Coding | None }
ResourceQuestionnaireSubmitRequest{ results, resource_id: UUID4 }; its results have no body_site

Form submission​

SpecRoleKey fields / behaviour
BaseFormSubmissionSpecshared__model__ = FormSubmission, id: UUID4 | None
FormSubmissionUpdateSpecwrite · updatestatus: FormSubmissionStatusChoices, response_dump: dict
FormSubmissionWriteSpecwrite · createAdds questionnaire: UUID4 (resolved by external_id), patient: UUID4, encounter: UUID4 | None. Refuses referral questionnaires. When an encounter is given, the patient is set to the encounter's patient
FormSubmissionReadSpecread · detailid, status, response_dump, created_date, modified_date, created_by, updated_by

Questionnaire response template​

The template specs live in resources/questionnaire_response_template/spec.py and are documented in the Questionnaire Response Template reference.

FormSubmission​

FieldType
questionnaireFK Questionnaire (CASCADE)
patientFK emr.Patient (CASCADE)
encounterFK emr.Encounter (CASCADE, nullable)
statusCharField(255), a FormSubmissionStatusChoices value
response_dumpJSONField, default {}

QuestionnaireResponse​

FieldType
questionnaireFK Questionnaire (CASCADE, nullable): the current row of the questionnaire
revisionIntegerField, default 1: the questionnaire's internal_revision at submit time
subject_idUUIDField
responsesJSONField, default []: the raw submitted results
cleaned_responseJSONField, default {}: answers keyed by link ID
structured_responsesJSONField, default {}
structured_response_typeCharField, nullable
patientFK emr.Patient (CASCADE)
encounterFK emr.Encounter (CASCADE, nullable)
form_submissionFK FormSubmission (CASCADE, nullable)
statusCharField(255), default "completed"

QuestionnaireOrganization and QuestionnaireFacilityOrganization​

Through-models that link a questionnaire to organizations: the first to an instance Organization (instance scope), the second to a FacilityOrganization (facility scope). Neither overrides save(); the viewset rebuilds the caches after it changes the links.

ModelFields
QuestionnaireOrganizationquestionnaire → FK Questionnaire (CASCADE); organization → FK Organization (CASCADE)
QuestionnaireFacilityOrganizationquestionnaire → FK Questionnaire (CASCADE); organization → FK FacilityOrganization (CASCADE)

The specs in questionnaire_organization.py exclude both foreign keys from serialization: the write spec takes organization: UUID4, and the read spec returns organization: dict.

QuestionnaireResponseTemplate​

FieldType
facilityFK facility.Facility (CASCADE, nullable)
nameCharField(255)
descriptionTextField, default ""
template_dataJSONField, default {}
questionnaireFK Questionnaire (CASCADE, nullable, default None)
facility_organizationsArrayField[int], default []
usersArrayField[int], default []
available_keysArrayField[CharField(255)], default []; server-maintained

Methods & save behaviour​

Revisions on update​

QuestionnaireUpdateSpec.perform_extra_deserialization hashes the incoming questions and compares the hash with the stored questions_hash. If they differ, it saves a copy of the old row with a new external_id and latest_revision set to the current row, increments internal_revision, and stores the new hash. If they match, no revision is made, so an update of the title, slug, description, or status alone keeps the revision.

A past revision cannot be updated ("This Questionnaire is a past revision, please update the latest revision") or submitted to.

Update lock​

handle_update takes a QuestionnaireLock on the row. A concurrent update fails with "Questionnaire update failed, try again after a while".

Create​

QuestionnaireCreateSpec.perform_extra_deserialization resolves the facility (or the facility organization and its facility), sets questions_hash, and for facility_organization scope sets internal_organization_cache. After the save, the viewset calls sync_facility_org_cache().

Access cache sync​

MethodScopeResult
sync_facility_org_cache()facilityinternal_organization_cache = the facility's root organization, each linked department, and each linked department's parents. Called after create and by set_facility_organizations
sync_facility_org_cache()facility_organizationinternal_organization_cache = the organization and its parents
sync_org_cache()instanceorganization_cache = each linked Organization and its parents. Called by set_organizations

Each method de-duplicates the ids and saves only its cache field.

Questionnaire.get_questions_by_id()​

Walks the questions tree, recursing into nested questions, and returns a { str(question_id): question } dict. The result is memoized on the instance in _questions_by_id_cache. If questions is not a list, it returns an empty dict.

QuestionnaireResponse.resolved_questionnaire and render_responses()​

resolved_questionnaire returns the linked questionnaire when the response's revision equals its internal_revision; otherwise it returns the past revision whose latest_revision is that questionnaire and whose internal_revision equals the response's revision.

render_responses() pairs each stored answer with its question from that revision. It skips answers whose question_id is not in that revision, and returns an empty list when there are no responses or no questionnaire.

Submission handling​

submit and handle_response() in utils.py run these steps:

  1. Refuse referral questionnaires and past revisions.
  2. For an encounter questionnaire, require an encounter of the given patient, refuse an encounter from another facility when the questionnaire has a facility, and check the encounter submit permission. For other subject types, refuse an encounter and check the patient submit permission.
  3. Refuse the submission if the questionnaire status is not active (questionnaire_inactive) or if it has no answers (questionnaire_empty).
  4. Drop questions whose enable_when conditions fail; an answer to a dropped question is an enable_when_failed error. A condition whose answer is an object compares coding system and code.
  5. Validate each answer: required, the type checks in QuestionType, value-set membership, and quantity units. Any failure aborts with an errors payload.
  6. Refuse a patient questionnaire that is not instance-level, then resolve the encounter and the patient.
  7. Create the QuestionnaireResponse with responses and cleaned_response, and store the questionnaire's internal_revision in revision.
  8. When an encounter is present, bulk-create the derived Observations, linked to the response.
  9. If form_submission is given, it must be a draft for the same questionnaire and patient with no response yet; link the response to it.
  10. Evaluate the questionnaire's actions with the patient or encounter questionnaire context, and return the result under _actions.

submit_resource serves location, device, and facility questionnaires. It checks the resource permission and that the resource's facility matches the questionnaire's facility, then runs the same answer validation and writes a FacilityResourceQuestionnaireResponse and FacilityResourceObservation rows instead.

API integration notes​

  • Routes: /api/v1/questionnaire/ (list, create) and /api/v1/questionnaire/<id>/ (retrieve, update, delete), plus upsert, the favorites actions (favorite_lists, add_favorite, remove_favorite), and the detail actions submit, submit_resource, get_facility_organizations, set_facility_organizations, get_organizations, and set_organizations.
  • Questionnaires are looked up by external_id (UUID), not by slug.
  • List filters: title (contains, case-insensitive), subject_type (multi-select), auth_context (exact, case-insensitive), facility, facility_isnull, status (exact, case-insensitive), parent_revision, facility_or_instance, slug (exact, case-insensitive). Without parent_revision, the list returns only current rows; with it, the past revisions of that questionnaire. facility_or_instance returns the facility's rows plus rows with no facility.
  • The list returns the questionnaires whose organization_cache overlaps an instance organization where the caller holds a role with "Can Read Questionnaires", or whose internal_organization_cache overlaps such a facility organization, plus the caller's own user questionnaires. Other actions run per-object checks instead.
  • facility scope: retrieve needs "Can Read Questionnaires" in a facility organization listed in internal_organization_cache; create, update, and delete need "Can Create/Update Questionnaires" in the facility's root organization.
  • facility_organization scope: read or write permission in that organization or one of its parents. user scope: the permission in any organization of the facility, and only the creator can update or delete.
  • instance scope: no facility permission allows create, update, delete, or organization changes.
  • On create and update, each action instruction must be authorized for the caller; an unknown or unauthorized instruction is a validation error.
  • get_facility_organizations and set_facility_organizations work only for facility questionnaires, and both run the update authorization, so reading the linked departments also needs write access. set_facility_organizations takes { facility_organizations: list[UUID4] } and replaces every link; each department must belong to the questionnaire's facility (404 otherwise).
  • get_organizations and set_organizations work only for instance questionnaires.
  • Delete is a soft delete with the update authorization. The frontend does not call it.
  • Server-maintained, and in no write spec: internal_revision, latest_revision, questions_hash, organization_cache, internal_organization_cache, and QuestionnaireResponse.revision.
  • Submitting validates answers server-side and, when an encounter is present, creates Observations. QuestionnaireResponseUpdate changes only the response status, for example to entered_in_error.