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
| Model | Purpose |
|---|---|
Questionnaire | A form definition: questions, subject type, status, scope, and revision chain |
FormSubmission | A submission record for a questionnaire, a patient, and an optional encounter, with a status and a response dump |
QuestionnaireResponse | The stored answers for a subject, with the questionnaire revision they were answered with |
QuestionnaireOrganization | Links an instance questionnaire to an instance Organization |
QuestionnaireFacilityOrganization | Links a facility questionnaire to a FacilityOrganization (department) |
QuestionnaireResponseTemplate | A reusable template of answers (template_data) for a questionnaire; see the Questionnaire Response Template reference |
All six extend EMRBaseModel.
Questionnaire fields
Definition
| Field | Type | Req | Notes |
|---|---|---|---|
version | CharField(255) | no | The write spec defaults it to "1.0" and freezes it there. It is not the revision number; see internal_revision |
slug | CharField(255) | no | Defaults 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 |
title | CharField(255) | yes | Stored stripped; a blank or whitespace-only title is rejected |
description | TextField | no | Defaults to "" |
subject_type | CharField(255) | yes | SubjectType enum. Set on create only |
status | CharField(255) | yes | QuestionnaireStatus enum |
styling_metadata | JSONField | no | Defaults to {}. Not validated |
questions | JSONField | yes | Defaults to {} in the database; the API takes a list[Question] tree. See Question nested shape |
actions | JSONField | no | Defaults to []. On create and update, each action's instructions must be authorized for the caller |
Scope and revision
| Field | Type | Req | Notes |
|---|---|---|---|
auth_context | CharField(255) | yes on create | QuestionnaireAuthContext enum. The model default is "instance"; the create spec requires it |
facility | FK facility.Facility (CASCADE, nullable) | scope-dependent | Required for facility and user scopes. For facility_organization scope, Care copies the organization's facility |
facility_organization | FK emr.FacilityOrganization (CASCADE, nullable) | scope-dependent | Required for facility_organization scope |
internal_revision | IntegerField | — | Default 1. Server-maintained: incremented when an update changes the questions |
latest_revision | FK self (CASCADE, nullable) | — | null on the current row. On a past revision, points to the current row |
questions_hash | CharField(255) | — | SHA-256 of the questions serialized as JSON with sorted keys. Set on create, compared on update |
Access caches
| Field | Type | Req | Notes |
|---|---|---|---|
organization_cache | ArrayField[int] | — | Instance Organization ids. Server-maintained; see Access cache sync |
internal_organization_cache | ArrayField[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.
| Scope | Unique within | Constraint |
|---|---|---|
instance | All instance questionnaires | unique_questionnaire_slug_instance |
facility | The facility | unique_questionnaire_slug_facility |
facility_organization | The facility organization | unique_questionnaire_slug_facility_organization |
user | The facility and the creator | unique_questionnaire_slug_user |
Past revisions keep the slug of the row they were copied from.
Enum values
QuestionnaireAuthContext values
| Value | Meaning |
|---|---|
instance | Shared across the Care instance. No facility permission allows creating, updating, or deleting it |
facility | Belongs to one facility; managed under the facility's settings |
facility_organization | Belongs to one facility organization. The frontend has no screen for this scope |
user | Belongs to its creator within a facility. The frontend has no screen for this scope |
QuestionnaireStatus values
| Value | Meaning |
|---|---|
active | Can be submitted |
retired | Cannot be submitted |
draft | Cannot 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.
| Value | Notes |
|---|---|
patient | Instance scope only. Submitted through submit without an encounter |
encounter | Submitted through submit with an encounter. For a questionnaire that has a facility, the encounter must be in that facility |
referral | Refused by submit, submit_resource, and form submissions; submitted through a referral |
location | Submitted through submit_resource |
device | Submitted through submit_resource |
facility | Submitted through submit_resource |
QuestionType values
The type of each question (Question.type). The commented-out members open_choice, attachment, and reference are not implemented.
| Value | Notes |
|---|---|
group | Container; must have at least one sub-question |
boolean | On submit, the value must be true, false, 1, or 0 |
decimal | On submit, the value must parse as a decimal |
integer | On submit, the value must parse as an integer |
string | |
text | On submit, length capped by settings.MAX_QUESTIONNAIRE_TEXT_RESPONSE_SIZE |
display | Display only; collects no answer |
date | On submit, an ISO date |
dateTime | On submit, an ISO date-time that includes a timezone |
time | On submit, %H:%M:%S |
choice | Requires answer_option or answer_value_set. On submit, the value must be one of the options, or a coding in the value set |
url | On submit, the value needs a scheme and a host |
quantity | Requires answer_option or answer_value_set. On submit, each answer needs a unit |
structured | Skipped 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).
| Value | Meaning |
|---|---|
all | Enabled only if every condition passes. Used when the field is absent |
any | Enabled 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:
| Field | Type | Req | Default | Notes |
|---|---|---|---|---|
link_id | str | yes | — | Human-readable link ID; unique across the whole tree |
id | UUID4 | UUID5 | yes | — | Machine ID supplied by the client; unique across the whole tree |
code | Coding bound to value set system-observation | no | None | |
collect_time | bool | no | false | Collect a timestamp |
collect_performer | bool | no | false | Collect a performer |
text | str | yes | — | Question text |
description | str | None | no | None | |
type | QuestionType | yes | — | See values |
structured_type | str | None | no | None | |
enable_when | list[EnableWhen] | None | no | None | Conditional display rules |
enable_behavior | EnableBehavior | None | no | None | |
disabled_display | DisabledDisplay | None | no | None | |
collect_body_site | bool | None | no | None | |
collect_method | bool | None | no | None | |
required | bool | None | no | None | |
repeats | bool | None | no | None | |
read_only | bool | None | no | None | |
max_length | int | None | no | None | |
answer_constraint | AnswerConstraint | None | no | None | |
answer_option | list[AnswerOption] | None | no | None | Inline choices |
answer_value_set | ValueSetConfig | None | no | None | { 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_observation | bool | None | no | None | |
unit | Coding bound to value set system-ucum-units | no | None | |
questions | list[Question] | no | [] | Recursive children |
formula | str | None | no | None | |
styling_metadata | dict | no | {} | |
templates | list[TemplateConfig] | no | [] | |
is_component | bool | no | false |
Validation on each Question:
choiceandquantityquestions must haveanswer_optionoranswer_value_set.groupquestions must have at least one sub-question.answer_value_setmust resolve to an existing value set, byexternal_idor by instanceslug.
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
| Spec | Shape |
|---|---|
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
| Spec | Role | Key fields / behaviour |
|---|---|---|
QuestionnaireBaseSpec | shared | __model__ = Questionnaire |
QuestionnaireWriteSpec | write (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 |
QuestionnaireCreateSpec | write · create | Adds 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 |
QuestionnaireUpdateSpec | write · update | The write spec fields only: no subject_type, auth_context, facility, or facility_organization. Creates a past revision when the questions change |
QuestionnaireReadSpec | read · list / detail | id (= 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 |
QuestionnaireSpec | unused | An 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
| Spec | Role | Key fields / behaviour |
|---|---|---|
EMRQuestionnaireResponseBase | shared | __model__ = QuestionnaireResponse |
QuestionnaireResponseUpdate | write · update | status: QuestionnaireResponseStatusChoices (default completed) |
QuestionnaireResponseReadSpec | read · detail | id, 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.
| Spec | Shape |
|---|---|
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
| Spec | Role | Key fields / behaviour |
|---|---|---|
BaseFormSubmissionSpec | shared | __model__ = FormSubmission, id: UUID4 | None |
FormSubmissionUpdateSpec | write · update | status: FormSubmissionStatusChoices, response_dump: dict |
FormSubmissionWriteSpec | write · create | Adds 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 |
FormSubmissionReadSpec | read · detail | id, 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.
Related models
FormSubmission
| Field | Type |
|---|---|
questionnaire | FK Questionnaire (CASCADE) |
patient | FK emr.Patient (CASCADE) |
encounter | FK emr.Encounter (CASCADE, nullable) |
status | CharField(255), a FormSubmissionStatusChoices value |
response_dump | JSONField, default {} |
QuestionnaireResponse
| Field | Type |
|---|---|
questionnaire | FK Questionnaire (CASCADE, nullable): the current row of the questionnaire |
revision | IntegerField, default 1: the questionnaire's internal_revision at submit time |
subject_id | UUIDField |
responses | JSONField, default []: the raw submitted results |
cleaned_response | JSONField, default {}: answers keyed by link ID |
structured_responses | JSONField, default {} |
structured_response_type | CharField, nullable |
patient | FK emr.Patient (CASCADE) |
encounter | FK emr.Encounter (CASCADE, nullable) |
form_submission | FK FormSubmission (CASCADE, nullable) |
status | CharField(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.
| Model | Fields |
|---|---|
QuestionnaireOrganization | questionnaire → FK Questionnaire (CASCADE); organization → FK Organization (CASCADE) |
QuestionnaireFacilityOrganization | questionnaire → 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
| Field | Type |
|---|---|
facility | FK facility.Facility (CASCADE, nullable) |
name | CharField(255) |
description | TextField, default "" |
template_data | JSONField, default {} |
questionnaire | FK Questionnaire (CASCADE, nullable, default None) |
facility_organizations | ArrayField[int], default [] |
users | ArrayField[int], default [] |
available_keys | ArrayField[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
| Method | Scope | Result |
|---|---|---|
sync_facility_org_cache() | facility | internal_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_organization | internal_organization_cache = the organization and its parents |
sync_org_cache() | instance | organization_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:
- Refuse referral questionnaires and past revisions.
- 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.
- Refuse the submission if the questionnaire
statusis notactive(questionnaire_inactive) or if it has no answers (questionnaire_empty). - Drop questions whose
enable_whenconditions fail; an answer to a dropped question is anenable_when_failederror. A condition whose answer is an object compares coding system and code. - Validate each answer:
required, the type checks in QuestionType, value-set membership, andquantityunits. Any failure aborts with anerrorspayload. - Refuse a patient questionnaire that is not instance-level, then resolve the encounter and the patient.
- Create the
QuestionnaireResponsewithresponsesandcleaned_response, and store the questionnaire'sinternal_revisioninrevision. - When an encounter is present, bulk-create the derived Observations, linked to the response.
- If
form_submissionis given, it must be a draft for the same questionnaire and patient with no response yet; link the response to it. - Evaluate the questionnaire's
actionswith 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), plusupsert, the favorites actions (favorite_lists,add_favorite,remove_favorite), and the detail actionssubmit,submit_resource,get_facility_organizations,set_facility_organizations,get_organizations, andset_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). Withoutparent_revision, the list returns only current rows; with it, the past revisions of that questionnaire.facility_or_instancereturns the facility's rows plus rows with no facility. - The list returns the questionnaires whose
organization_cacheoverlaps an instance organization where the caller holds a role with "Can Read Questionnaires", or whoseinternal_organization_cacheoverlaps such a facility organization, plus the caller's ownuserquestionnaires. Other actions run per-object checks instead. facilityscope: retrieve needs "Can Read Questionnaires" in a facility organization listed ininternal_organization_cache; create, update, and delete need "Can Create/Update Questionnaires" in the facility's root organization.facility_organizationscope: read or write permission in that organization or one of its parents.userscope: the permission in any organization of the facility, and only the creator can update or delete.instancescope: 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_organizationsandset_facility_organizationswork only forfacilityquestionnaires, and both run the update authorization, so reading the linked departments also needs write access.set_facility_organizationstakes{ facility_organizations: list[UUID4] }and replaces every link; each department must belong to the questionnaire's facility (404 otherwise).get_organizationsandset_organizationswork only forinstancequestionnaires.- 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, andQuestionnaireResponse.revision. - Submitting validates answers server-side and, when an encounter is present, creates Observations.
QuestionnaireResponseUpdatechanges only the response status, for example toentered_in_error.
Related
- Source: questionnaire.py on GitHub
- Spec: questionnaire/spec.py · response spec · submit utils · form_submission spec
- Concept: Questionnaire
- Reference: Base model
- Reference: Questionnaire Response
- Reference: Questionnaire Response Template
- Reference: ValueSet
- Reference: Patient
- Reference: Encounter
- Reference: Observation
- Reference: Organization
- Reference: Favorites