Skip to main content
Version: 3.1

Allergy intolerance

Technical reference for the AllergyIntolerance module in Care EMR. For the plain-language view, see the Allergy intolerance concept.

Source:

The Django model is the storage layer. It stores the allergen (code) and the onset (onset) as JSON fields, and the coded fields as text columns.

The Pydantic resource specs give the JSON fields their shape. They also define the enums, the required fields, the bound value set, and the read and write schemas.

The viewset defines the API actions, the authorization checks, and the copy that Care keeps on the old encounter when an update moves an allergy.

Models​

ModelPurpose
AllergyIntoleranceOne allergy of one patient. It is linked to one encounter: the encounter named in its create request or in its latest update. A copy stays on the encounter that the original was linked to before an update moved it.

AllergyIntolerance extends EMRBaseModel. Through it, each allergy has external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.

AllergyIntolerance fields​

Coded fields​

FieldStorageNull / defaultSpec typeNotes
clinical_statusCharField(100)null=True, blank=TrueClinicalStatusChoices on write, str on readRequired on create and on update
verification_statusCharField(100)null=True, blank=TrueVerificationStatusChoices on write, str on readRequired on create and on update
categoryCharField(100)null=True, blank=TrueCategoryChoices on create, str on readRequired on create. Not in the update spec, so it cannot change after creation
criticalityCharField(100)null=True, blank=TrueCriticalityChoices on write, str on readRequired on create and on update
allergy_intolerance_typeCharField(20)default="allergy"AllergyIntoleranceTypeOptions on write, str on readOptional on create and on update; the spec default is allergy

Allergen​

FieldStorageNull / defaultSpec typeNotes
codeJSONFielddefault=dict, null=False, blank=FalseValueSetBoundCoding bound to system-allergy-code on create, Coding on readRequired on create. Not in the update spec, so it cannot change after creation. Shape and value set below

Timing​

FieldStorageNull / defaultSpec typeNotes
onsetJSONFielddefault=dictAllergyIntoleranceOnSetSpecOptional on create, default {}. Not in the update spec, so it cannot change after creation. Shape below
recorded_dateDateTimeFieldnull=True, blank=Truedatetime | NoneOptional on create. Not in the update spec, so it cannot change after creation
last_occurrenceDateTimeFieldnull=True, blank=Truedatetime | NoneOptional on create and on update
FieldStorageNull / defaultSpec typeNotes
patientFK → emr.Patienton_delete=CASCADENot in any specSet on create to the patient of the encounter in the request
encounterFK → emr.Encounteron_delete=CASCADEUUID4 (the encounter's external_id)Required on create and on update. The encounter must exist. An update links the allergy to the encounter in the request
noteTextFieldnull=True, blank=Truestr | NoneOptional on create and on update
copied_fromBigIntegerFielddefault=None, null=True, blank=TrueNot in any specInternal ID of the original allergy when this row is a copy; null for an original. Set by Care when an update moves an allergy to another encounter

Inherited from EMRBaseModel​

FieldStorageNotes
external_idUUIDField(default=uuid4, unique=True, db_index=True)The allergy's public ID. Returned as id
created_date, modified_dateDateTimeFieldReturned on read
deletedBooleanField(default=False, db_index=True)Soft-delete flag. Normal queries hide soft-deleted rows
created_by, updated_byFK → users.User, on_delete=SET_NULLcreated_by: the user who created the allergy. updated_by: the user who last created or updated it. Both returned on read
historyJSONField(default=dict)Updates do not write to it
metaJSONField(default=dict)Every spec carries meta, default {}

Enum values​

The specs accept only these values on write. The second column is the label that the Care frontend shows for the value.

ClinicalStatusChoices values​

ValueLabel in the Care frontend
activeActive
inactiveInactive
resolvedResolved

VerificationStatusChoices values​

ValueLabel in the Care frontend
unconfirmedUnconfirmed
presumedPresumed
confirmedConfirmed
refutedRefuted
entered_in_errorEntered in Error

CategoryChoices values​

ValueLabel in the Care frontend
foodFood
medicationMedication
environmentEnvironment
biologicBiologic

CriticalityChoices values​

ValueLabel in the Care frontend
lowLow
highHigh
unable_to_assessUnable to Assess

AllergyIntoleranceTypeOptions values​

ValueNotes
allergySpec default on create and on update
intolerance

The Care frontend never sends a type or an onset. Every allergy recorded from the Care UI has type allergy and no onset.

Nested JSON shapes​

code: Coding​

code is one Coding. Its code key is required; system, version and display are optional. Care rejects any other key.

Coding
{
"system": str | null, optional
"version": str | null, optional
"code": str, required
"display": str | null optional
}

Bound value set​

NameSlugStatusDefault content
Allergysystem-allergy-codeactiveSNOMED CT (http://snomed.info/sct) concepts that are is-a descendants of the eight concepts below
SNOMED CT codeDisplay name
105590001Substance
418038007Propensity to adverse reactions to substance
267425008Lactose intolerance
29736007Syndrome of carbohydrate intolerance
340519003Lysine intolerance
190753003Sucrose intolerance
413427002Acquired fructose intolerance
716186003No known allergy
  • On create, Care checks code against a value set with the slug system-allergy-code. A code outside it fails with "Code does not exist in the valueset".
  • If the value set is not in the database, the error is "Valueset does not exist in care, Resync valuesets".
  • Value sets with the slug system-allergy-code can exist once instance-wide, and again per facility, per facility organization and per user.
  • On save, Care checks the code against the first value set it finds with that slug, without regard to facility.
  • The allergen search (POST /api/v1/valueset/expand_slug/) passes the current facility. It uses the user's preferred value set for that facility if there is one.
  • Otherwise the search chooses among that facility's value sets and the instance-wide ones with the slug.
  • So the search and the save can use different value sets. When a facility has its own allergen list, the search offers its codes.
  • Saving an allergen that is only in the facility's list fails with "Code does not exist in the valueset".
  • It is a system value set. The sync command writes it to the database and leaves an existing copy unchanged unless told to overwrite it.
  • The stored value set can be edited after the sync, so a deployment's content can differ from the default above.
  • 105590001 (Substance) is also the only root of Care's "Substance" value set, slug system-substance.
  • Every signed-in user can read the system value set.

onset: AllergyIntoleranceOnSetSpec​

Onset is optional on create and defaults to {}. When an onset object is sent, its note is required. The update spec has no onset.

AllergyIntoleranceOnSetSpec
{
"onset_datetime": datetime, optional, default null
"onset_age": int, optional, default null
"onset_string": str, optional, default null
"note": str required, no default
}

AllergyIntolerance links to other models as follows. copied_from holds an internal ID, not a foreign key.

AllergyIntolerance
patient → FK emr.Patient (CASCADE)
encounter → FK emr.Encounter (CASCADE)
created_by → FK users.User (SET_NULL)
updated_by → FK users.User (SET_NULL)
copied_from → BigIntegerField: internal ID of the original AllergyIntolerance

Each create and each update through the API also writes a questionnaire response entry for the allergy. See "Methods & save behaviour" below.

Resource specs (API schema)​

Every spec extends EMRResource. BaseAllergyIntoleranceSpec ties the specs to AllergyIntolerance and leaves patient and encounter out of the automatic field mapping.

The viewset uses the write spec for create, the update spec for update, and the read spec for reads. It sets no retrieve spec, so one allergy and the list return the same fields.

SpecRoleFields
BaseAllergyIntoleranceSpecshared baseid (UUID4, optional), meta (dict, default {})
AllergyIntoleranceWriteSpecwrite · createclinical_status, verification_status, category, criticality, encounter, code, last_occurrence?, recorded_date?, onset?, allergy_intolerance_type?, note?
AllergyIntoleranceUpdateSpecwrite · updateclinical_status, verification_status, criticality, encounter, last_occurrence?, note?, allergy_intolerance_type?
AllergyIntoleranceReadSpecread · list and detailid, clinical_status, verification_status, category, criticality, code, encounter, onset, last_occurrence, recorded_date, note, allergy_intolerance_type, created_by, updated_by, created_date, modified_date, meta
AllergyIntoleranceOnSetSpecnested · shape of onsetonset_datetime?, onset_age?, onset_string?, note

Create: AllergyIntoleranceWriteSpec​

The body of a create request, and of an upsert entry without id.

{
"encounter": UUID, required; the encounter must exist
"code": Coding, required; in value set system-allergy-code
"clinical_status": ClinicalStatusChoices, required
"verification_status": VerificationStatusChoices, required
"category": CategoryChoices, required
"criticality": CriticalityChoices, required
"last_occurrence": datetime | null, optional, default null
"recorded_date": datetime | null, optional, default null
"onset": AllergyIntoleranceOnSetSpec, optional, default {}
"allergy_intolerance_type": AllergyIntoleranceTypeOptions, optional, default "allergy"
"note": str | null optional, default null
}
  • No spec has a patient or a copied_from field. Care sets patient from the encounter on create, and sets copied_from only on copies.
  • Care does not write id or external_id from the body.
  • A successful create answers HTTP 200, not 201, with the new allergy in the read format.

Update: AllergyIntoleranceUpdateSpec​

The body of an update request, and of an upsert entry with id.

{
"encounter": UUID, required; the encounter must exist
"clinical_status": ClinicalStatusChoices, required
"verification_status": VerificationStatusChoices, required
"criticality": CriticalityChoices, required
"last_occurrence": datetime | null, optional, default null
"note": str | null, optional, default null
"allergy_intolerance_type": AllergyIntoleranceTypeOptions optional, default "allergy"
}
  • code, category, onset and recorded_date are not in the update spec, so they cannot change after creation.
  • The update keeps encounter from the request body, so every update names an encounter.
  • The allergy is linked to the encounter in the request. If that is a different encounter, Care keeps a copy on the old one.
  • PUT and PATCH run the same update code. A successful update answers HTTP 200 with the updated allergy in the read format.
  • Care does not write a value that equals the field's default. See "Methods & save behaviour" below.

Read: AllergyIntoleranceReadSpec​

The list and the detail route return each allergy in this shape.

{
"id": UUID (the allergy's external_id),
"code": Coding,
"clinical_status": str,
"verification_status": str,
"category": str,
"criticality": str,
"encounter": UUID (the encounter's external_id),
"onset": AllergyIntoleranceOnSetSpec, default {},
"last_occurrence": datetime | null,
"recorded_date": datetime | null,
"note": str | null,
"allergy_intolerance_type": str,
"created_by": UserSpec | null,
"updated_by": UserSpec | null,
"created_date": datetime,
"modified_date": datetime,
"meta": object
}
  • The read spec types the coded fields as str. Reads build the spec with model_construct, which does not validate the values again.
  • Care adds created_by and updated_by when it reads the allergy. Each is a user object (UserSpec, read from the user cache), or null when not set.
  • A UserSpec carries id, first_name, last_name, phone_number, prefix, suffix, last_login, profile_picture_url, gender, username, mfa_enabled, deleted, role_orgs, communication and qualification.
  • The response has no patient and no copied_from.

Validation​

  • encounter, on create and on update: no encounter with that ID gives "Encounter not found".
  • code, on create: the code must be in system-allergy-code. The errors are listed under "Bound value set".
  • onset: when it is sent, onset.note is required.
  • clinical_status, verification_status, category, criticality and allergy_intolerance_type accept only the enum values above.

A failed validation answers HTTP 400 with an errors list. Each error names the field path in loc and gives a msg.

HTTP 400
{
"errors": [
{ "loc": ["clinical_status"], "msg": "Input should be 'active', 'inactive' or 'resolved'" },
{ "loc": ["criticality"], "msg": "Field required" },
{ "loc": ["onset", "note"], "msg": "Field required" }
]
}

The three errors above are separate examples: a wrong clinical status, a missing criticality, and an onset without a note.

Methods & save behaviour​

Create​

  • Care checks that the encounter exists, links the allergy to it, and sets patient to that encounter's patient.
  • Care sets both created_by and updated_by to the user who sent the request.
  • Care writes a questionnaire response entry with submit type CREATE. It holds the allergy's ID, the type allergy_intolerance, and the user.

Update​

  • Care links the allergy to the encounter in the request.
  • If that encounter differs from the stored one, Care first saves a copy of the allergy as it was. The copy stays on the old encounter, and its copied_from holds the original's internal ID.
  • If the new encounter already holds an earlier copy of this allergy, Care deletes that copy.
  • Care sets updated_by to the user who sent the request.
  • Care writes a questionnaire response entry with submit type UPDATE. It holds the allergy's ID, the type allergy_intolerance, and the user.
  • Care does not keep a field-by-field history of changes. The code marks this as a to-do.

Copies on earlier encounters​

  • Reads with patient-level access return only original allergies, never the copies left on old encounters.
  • Without patient-level access, a list must name an encounter with ?encounter=. It then returns the allergies linked to that encounter, copies included.
  • On each save, the Care frontend's allergy form sends every saved allergy it loaded (up to 100) as an update, with the current encounter.
  • So each save of the form links those allergies to the current encounter. Care keeps a copy of each one that was linked to another encounter.
  • This is by design: users re-confirm the patient's allergy list at every encounter where they save the allergy form.

Care skips values equal to a default​

  • When Care saves a spec, it writes only the fields whose values differ from the field's default. It skips a value that equals the default.
  • It writes only database fields that are not excluded and are not id or external_id. Then it runs the spec's extra save step.
  • In the update spec, the defaults are null for note and last_occurrence, and allergy for allergy_intolerance_type. An update that sends one of these values does not write that field.
  • Care accepts such an update, but keeps the stored value. Setting the type back to allergy, or note or last_occurrence to empty, leaves the old value.

No delete​

  • Care has no action that deletes an allergy.
  • The Care frontend marks an allergy as entered in error with an update that sets verification_status to entered_in_error.
  • The allergy lists of the Care frontend leave those allergies out with exclude_verification_status=entered_in_error.

API integration notes​

Routes​

All routes are under /api/v1/, nested under the patient. {patient} is the patient's external ID. Every request needs a signed-in user.

ActionMethod and pathRequest bodySuccess response
ListGET /api/v1/patient/{patient}/allergy_intolerance/Nonecount and results (read format)
View oneGET /api/v1/patient/{patient}/allergy_intolerance/{id}/NoneThe allergy (read format)
CreatePOST /api/v1/patient/{patient}/allergy_intolerance/Write specHTTP 200, the new allergy (read format)
UpdatePUT or PATCH /api/v1/patient/{patient}/allergy_intolerance/{id}/Update specHTTP 200, the updated allergy (read format)
UpsertPOST /api/v1/patient/{patient}/allergy_intolerance/upsert/datapoints: write or update spec, for each entryHTTP 200, a list of the created or updated allergies, in request order
DeleteNoneNoneNone
  • {id} is the allergy's id, as reads return it.
  • The list, view and update routes reach only allergies of the patient in the URL.
  • In an upsert, Care looks up the allergy to update by its id among all allergies, not only those of the patient in the URL.

List filters, ordering and pages​

Query parameterEffect
encounterEncounter external ID. Returns only allergies linked to that encounter
clinical_statusComma-separated values. Returns only these clinical statuses
exclude_clinical_statusComma-separated values. Leaves out these clinical statuses
verification_statusComma-separated values. Returns only these verification statuses
exclude_verification_statusComma-separated values. Leaves out these verification statuses
nameCase-insensitive search for part of code.display
limitRecords per page. Default 14, at most 200
offsetRecords to skip
orderingcreated_date or modified_date. A leading minus, as in -created_date, reverses the order
  • Without ordering, the list shows the most recently modified first.
  • Pages use CareLimitOffsetPagination. The list answers with count (the total) and results only; it has no next or previous fields.

Upsert​

The upsert takes a batch of entries in datapoints.

POST /api/v1/patient/{patient}/allergy_intolerance/upsert/
{
"datapoints": [
{ "id": "<allergy id>", ...AllergyIntoleranceUpdateSpec fields },
{ ...AllergyIntoleranceWriteSpec fields }
]
}
  • An entry with id updates that allergy. An entry without id creates a new one.
  • An upsert takes 1 to 100 entries by default. The setting MAX_DATAPOINTS_PER_UPSERT changes the limit.
  • No entries gives "No datapoints provided". Too many gives "Too many datapoints provided".
  • All or nothing: if any entry fails, Care saves none of them and returns 400 with a result for each entry.
  • A permission refusal inside an upsert does not answer 403. The refused entry's result is {"detail": "<message>"}, and the upsert answers 400.
  • On success, the upsert answers 200 with each created or updated allergy, in request order.
  • Each entry needs the permission of its action: create or update, as in the table below.

Authorization​

The table uses these terms:

  • "Closed": the encounter status is completed, cancelled, entered_in_error or discontinued. Any other status is open.
  • "A role on the patient": a role the user holds in an organization of an open encounter of the patient, or of its current location.
  • A role on the patient can also come from an organization the patient belongs to, or be given directly on the patient. Closed encounters give no roles on the patient.
  • "In the encounter": in one of the encounter's facility organizations, or in an organization of its current location.
  • The encounter's facility organizations include the organizations it is assigned to, their parents, and the facility's root organization "Administration".
ActionPermission (display name)Held whereRefusal message
List, view one"Can view clinical data about patients"A role on the patient. Copies on old encounters are left outNone: Care tries the next row
List, view one, with encounter and without the permission above"Can Read encounter related clinical data"In the encounter named in encounter. Returns only that encounter's allergies, copies included"Permission denied to user" when neither row applies
Create, and upsert entries without id"Can Update a Patient's data"A role on the patient in the URL"You do not have permission to create"
Update, and upsert entries with id"Update Encounter related clinical data"In the encounter named in the request body. Refused when that encounter is closed"You do not have permission to update encounter"
Update (PUT, PATCH): finding the allergyThe read access of the first two rowsWithout patient-level access, ?encounter= must name an encounter whose clinical data the user can read and to which the allergy is linkedAs for list and view
  • Outside an upsert, a refusal answers HTTP 403 with the body {"detail": "<message>"}, for example {"detail": "You do not have permission to create"}.
  • Create and upsert do not use the list's query, so neither needs the list's read access.
  • When the setting PATIENT_GLOBAL_EDIT_ACCESS_ENABLED is on, "Can Update a Patient's data" in any facility organization or organization is enough to write to every patient. The setting is off by default.
  • The Care frontend's allergy form re-sends every saved allergy as an update. So once the patient has a saved allergy, a save from the form needs "Update Encounter related clinical data" in the current encounter. New rows also need "Can Update a Patient's data".

Default roles per permission:

Permission (display name)SlugDefault roles
Can view clinical data about patientscan_view_clinical_dataStaff, Doctor, Nurse, Facility Admin
Can Read encounter related clinical datacan_read_encounter_clinical_dataDoctor, Nurse, Facility Admin
Can Update a Patient's datacan_write_patientStaff, Doctor, Nurse, Administrator, Facility Admin
Update Encounter related clinical datacan_write_encounter_clinical_dataDoctor, Nurse, Facility Admin

These role lists are the defaults in code. Each permission sync resets the built-in roles to them.

Errors​

  • Validation errors return HTTP 400 with an errors list. See "Validation" above.
  • Permission refusals return HTTP 403 with a detail message. Inside an upsert they return 400, with the detail in the entry's result.
  • An allergy or patient that cannot be found returns HTTP 404 with type object_not_found.
  • An encounter in the request body that does not exist fails validation: HTTP 400, "Encounter not found".
  • Without patient-level access, an encounter value that names no encounter with readable clinical data gets HTTP 403, "Permission denied to user".

Other routes and features that carry allergies​

  • Batch requests: POST /api/v1/batch_requests/ runs its requests in one transaction. If any request fails, it returns 400 and saves none of them.
  • A batch holds at most 20 requests by default (setting MAX_REQUESTS_PER_BATCH_REQUEST).
  • The batch endpoint checks only sign-in. Each request in it is authorized as if it were sent alone.
  • The Care frontend saves the allergy form as one batch request that carries one allergy upsert.
  • Questionnaires: the viewset is registered as the built-in questionnaire type allergy_intolerance, titled "Allergy Intolerance", with the patient as subject.
  • A custom questionnaire cannot use allergy_intolerance as its slug. The error is "Slug cannot shadow internal question types".
  • When a questionnaire is submitted, the backend skips answer validation for structured questions such as the allergy question.
  • Questionnaire responses: /api/v1/patient/{patient}/questionnaire_response lists the CREATE and UPDATE entries. The only_unstructured parameter leaves them out.
  • Reading those entries for an encounter needs patient-level clinical-data access, or clinical-data access on that encounter.
  • Referrals: an allergy can be attached to a referral as a resource of type allergy_intolerance, through the API only. The frontend's Add record picker offers only the types in REFERRAL_ATTACHABLE_RESOURCE_TYPES, which leave out allergies. The referral's Shared records list still shows an attached allergy, under Allergies.
  • To attach it, the user must be able to view the patient's clinical data, or the clinical data of the allergy's encounter.
  • Reports: encounter report templates offer an "Allergy Intolerances" field that lists the allergies of the encounter.
  • Its columns include Name, Clinical Status, Category, Verification Status, Criticality, Note, Occurrence and Allergy Intolerance Type.