Medication dispense
Technical reference for the MedicationDispense module in Care EMR. For what a medication dispense is in the product, see the Medication dispense concept.
A medication dispense records a quantity of one inventory item given out for a patient in an encounter. An inventory item is the stock of one product at one location. Saving a dispense reduces that stock, and it can create a charge item.
Source:
- Model:
care/emr/models/medication_dispense.py - Spec:
care/emr/resources/medication/dispense/spec.py - Spec:
care/emr/resources/medication/dispense/dispense_order.py - Viewset:
care/emr/api/viewsets/medication_dispense.py
The Django model stores dosage_instruction and substitution as JSON columns. The Pydantic resource specs define their shape, the enums, the validation and the read and write schemas. Enum values use underscores, such as in_progress.
Models
| Model | Purpose |
|---|---|
MedicationDispense | One dispense: a quantity of one inventory item for a patient in an encounter |
DispenseOrder | Groups dispenses for one patient at one location. See the Dispense order reference |
Both extend EMRBaseModel. It supplies external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.
MedicationDispense fields
In the tables below, the model type is the Django column and the spec type is what the API reads and writes. "Fixed" means that the update spec does not accept the field after create.
Status & classification
| Field | Model type | Spec type | Required (API) | Notes |
|---|---|---|---|---|
status | CharField(100) | MedicationDispenseStatus | Yes | A dispense in a cancelling status accepts no more updates. See status values |
not_performed_reason | CharField(100), nullable | MedicationDispenseNotPerformedReason | None | No | Can change after create |
category | CharField(100), nullable | MedicationDispenseCategory | None | No | Can change after create |
Timing & instructions
| Field | Model type | Spec type | Required (API) | Notes |
|---|---|---|---|---|
when_prepared | DateTimeField, nullable | datetime | None | No | Can change after create |
when_handed_over | DateTimeField, nullable | datetime | None | No | Can change after create |
note | TextField, nullable | str | None | No | Can change after create |
dosage_instruction | JSONField, default [], nullable | list[DosageInstruction], default [] | No | The DosageInstruction of medication requests. Can change after create |
substitution | JSONField, default {}, nullable | MedicationDispenseSubstitution | None | No | All three keys are required when sent. Can change after create |
Quantities
| Field | Model type | Spec type | Required (API) | Notes |
|---|---|---|---|---|
quantity | DecimalField(20, 6) | Decimal, whole number of at least 1 | Yes | Checked against the inventory item's stock on create. Fixed |
days_supply | DecimalField(20, 6), nullable | Decimal | None, whole number | No | Accepted on create, but no read returns it. Fixed |
Relationships
| Field | Model type | Spec type | Notes |
|---|---|---|---|
encounter | FK → Encounter, CASCADE | UUID4, required | patient is copied from it. Fixed |
patient | FK → Patient, CASCADE | Not accepted | Server-set from the encounter |
location | FK → FacilityLocation, CASCADE | UUID4, required | The dispensing location. Must be in the encounter's facility, or Care answers 404. The write permission is checked here. Fixed |
item | FK → InventoryItem, CASCADE | UUID4, required | Must be at a location of the encounter's facility, or Care answers 404. Fixed |
authorizing_request | FK → MedicationRequest, SET_NULL, nullable | UUID4 | None | Must be on the same encounter, or Care answers 404. Its status is not checked. Fixed. Care clears it on some cancellations, see Methods & save behaviour |
charge_item | FK → ChargeItem, CASCADE, nullable | Read only | Created by Care when the product has a charge item definition |
order | FK → DispenseOrder, CASCADE, nullable | UUID4 | None | An existing order. Can change after create. See Dispense order |
Two more write fields are not columns. fully_dispensed lives only for the save, and create_dispense_order creates or finds an order inline.
Enum values
MedicationDispenseStatus values
| Value |
|---|
preparation |
in_progress |
cancelled |
on_hold |
completed |
entered_in_error |
stopped |
declined |
MEDICATION_DISPENSE_CANCELLED_STATUSES lists cancelled, entered_in_error, stopped and declined. A dispense in one of these is final, and its quantity no longer counts against stock.
Among the other statuses there is no transition rule. A completed dispense can go back to in_progress.
MedicationDispenseNotPerformedReason values
| Value |
|---|
outofstock |
washout |
surg |
sintol |
sddi |
sdupther |
saig |
preg |
The backend holds only these codes, with no labels. The field is a plain enum, not a bound Coding, and no code relates it to the system-medication-not-given value set.
MedicationDispenseCategory values
| Value |
|---|
inpatient |
outpatient |
community |
discharge |
SubstitutionType values
Used in substitution.substitution_type. Codes only.
| Value |
|---|
E |
EC |
BC |
G |
TE |
TB |
TG |
F |
N |
SubstitutionReason values
Used in substitution.reason. Codes only.
| Value |
|---|
CT |
FP |
OS |
RR |
JSON field shapes
MedicationDispenseSubstitution shape
substitution = {
was_substituted: bool # required
substitution_type: SubstitutionType # required
reason: SubstitutionReason # required
}
DosageInstruction shape
dosage_instruction reuses the DosageInstruction spec of medication requests. Its fields, sub-types and bound value sets are on the Medication request reference.
Related models
DispenseOrder
A dispense order groups dispenses for one patient at one location. Its fields, statuses, rules and API are on the Dispense order reference.
MedicationDispense.order → FK DispenseOrder (CASCADE, nullable)
Charge item
When the dispensed product has a charge item definition, Care applies it and links the result in charge_item.
- The charge item is for the patient and the encounter, for the dispensed quantity.
- Its status is
billable, on the patient's default account at the facility. Care creates that account when the patient has no active, open account there. - It records that it comes from this dispense (
service_resourcemedication_dispense, with the dispense id). - When the medication request has a requester, the requester is the charge item's performer.
- Care checks no billing permission for this.
Resource specs (API schema)
Resource specs never copy foreign keys automatically. The shared dispense spec also lists patient, encounter, authorizing_request, item and location in __exclude__, and the hooks set them.
| Spec class | Role | Notes |
|---|---|---|
BaseMedicationDispenseSpec | shared | status, not_performed_reason, category, when_prepared, when_handed_over, note, dosage_instruction, substitution |
MedicationDispenseWriteSpec | write · create | Adds encounter, location, item (required), authorizing_request, quantity (required), days_supply, fully_dispensed, order and create_dispense_order |
MedicationDispenseUpdateSpec | write · update | The shared fields plus fully_dispensed and order |
MedicationDispenseReadSpec | read · list | Expands item, charge_item, location, authorizing_request and order. Adds quantity, created_date and modified_date. No created_by, updated_by or days_supply |
MedicationDispenseRetrieveSpec | read · detail | Adds encounter |
MedicationDispenseSubstitution | nested | The shape of substitution |
CreateDispenseOrder | write · nested | Inline order creation, see below |
CreateDispenseOrder
CreateDispenseOrder {
name: str | None
note: str | None
alternate_identifier: str # required
status: draft | in_progress # default draft
}
- Care looks for an order with the same
alternate_identifier, patient and location. A match joins the dispense to it. - A match that is not
draftorin_progressfails with "Prescription is not active". - With no match, Care creates an order for the patient at the dispensing location, in the encounter's facility. It takes the given status, name and note, and records the user as its creator.
- An order cannot be created as
completedthis way. - Sending both
orderandcreate_dispense_orderfails with "Cannot have both dispense order and create_dispense_order".
Methods & save behaviour
The model defines no save() or delete() override. The behaviour below lives in the specs and the viewset.
On create
- Care locks the order first and refuses an
abandonedorentered_in_errororder ("Dispense order is abandoned or entered in error"). An order id that does not exist fails before this, with HTTP 404. - Care then locks the inventory item. If another request holds it, Care answers HTTP 423 "The resource you are trying to access is locked".
- A quantity above the item's current stock fails with "Inventory item does not have enough stock". Care checks the quantity only. It does not refuse an expired or inactive lot.
- When the product has a charge item definition, Care creates the charge item, see Charge item.
- Care recalculates the item's stock. Dispenses in any status except the cancelling ones count against it.
- With an
authorizing_request,fully_dispensed: truesets itsdispense_statustocompleteandfalsesetspartial. Without the flag, the request stays as it is. - A dispense created directly in a cancelling status still needs enough stock and still gets a charge item, but it does not reduce stock.
- Care does not check the encounter's status, so a dispense can be recorded on a closed encounter.
On update
- A dispense in a cancelling status refuses any update ("No updates allowed on cancelled medication dispense").
- Care locks the old and the new order. Neither can be
abandonedorentered_in_error. If another request moved the dispense to another order meanwhile, Care answers HTTP 423. - A change into a cancelling status on a dispense with a charge item cancels that charge item. Care takes it off its draft invoice, recalculates the invoice totals and sets the charge item to
aborted. - If the charge item is on an invoice that is not a draft, the update fails with "Cannot cancel charge item in a non-draft invoice".
- In the same case, Care sets the request's
dispense_statustoincompleteand clearsauthorizing_request. Only a dispense with a charge item gets this reset. - Care then recalculates the item's stock and applies
fully_dispensedto the request again.
Order cancellation
Moving a dispense order to abandoned or entered_in_error cancels its dispenses, their charge items and their request links. See the Dispense order reference.
API integration notes
Endpoints
All paths are under /api/v1/. Dispenses are not nested under a patient or a facility.
| Method | Path | Action |
|---|---|---|
GET | medication/dispense/ | List. Needs location or encounter |
POST | medication/dispense/ | Create |
GET | medication/dispense/{id}/ | Retrieve |
PUT, PATCH | medication/dispense/{id}/ | Update. Both use MedicationDispenseUpdateSpec |
POST | medication/dispense/upsert/ | Batch create or update |
GET | medication/dispense/summary/ | Number of dispenses per encounter. Needs location or encounter |
There is no delete.
Authorization
| Action | Requirement |
|---|---|
Create, upsert items without id | "Write Medication Dispense" in the dispensing location's departments. No encounter permission is needed. Else 403 "You do not have permission to write medication dispenses" |
| Update | "Write Medication Dispense" for the dispense's own location |
| Retrieve | "Medication Dispense Read" for its location, or "Medication Dispense Read" on its encounter. Else 403 "You do not have permission to read medication dispense" |
List or summary with ?location= | "Medication Dispense Read" for that location. include_children=true adds the locations under it |
List or summary with ?encounter= | "Medication Dispense Read" on that encounter. Returns only that encounter's dispenses |
| List or summary with neither | HTTP 400 "Location or encounter is required" |
A location's departments are its parent location's departments, the departments it is linked to and their parents, and the facility's Administration department. An encounter-level check uses the encounter's departments and its current location's.
Listing the lots and stock of a location needs "Can Read Inventory Item" in that location's departments.
Default role lists from the permission definitions:
| Permission | Default roles |
|---|---|
| "Medication Dispense Read" | Facility Admin, Staff, Doctor, Nurse, Pharmacist |
| "Write Medication Dispense" | Facility Admin, Staff, Doctor, Nurse, Pharmacist |
| "Can Read Inventory Item" | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist |
The permission definitions also name an Admin role. Roles are matched by name, and the only role named Admin in the database is for role organizations, which the screen that links users to departments does not offer. The lists above leave it out.
A permission refusal is HTTP 403 with the message in detail. A business-rule refusal is HTTP 400 with errors: [{type: "validation_error", msg}]. A missing record is HTTP 404 with type object_not_found.
Filters and ordering
| Parameter | Meaning |
|---|---|
location | Dispensing location. Also selects the location read check |
include_children | With location, also dispenses at the locations under it |
encounter | Encounter id. Also selects the encounter read check |
status, exclude_status | Comma-separated statuses to keep or to leave out |
category | Category |
patient | Patient id |
item | Inventory item id |
authorizing_request | Medication request id |
authorizing_prescription | Prescription of the medication request |
order | Dispense order id |
ordering | created_date or modified_date. Without it, newest record first |
Lists are paginated with limit and offset (default 14, at most 200) and return count and results.
Upsert
POST medication/dispense/upsert/ takes {"datapoints": [...]}, at most 100 by default. An item with id is an update and an item without one is a create. All items run in one transaction: if any fails, nothing is saved and the response is HTTP 400.
Medication returns
A medication return is not a change to the dispense. Care 3.1 records it as a delivery order with a patient, at facility/{facility_id}/order/delivery/. See the Medication return and Supply delivery concepts.
- A returned item names a product and a quantity. Nothing links it to the dispense it reverses.
- A returned item that is completed adds its quantity to stock at the return's destination.
- Completing the return creates a refund invoice on the patient's default account.
- Returns use "Can Read Medication Returns" and "Can Write Medication Returns" at the destination, new in 3.1. By default, Facility Admin is the only role given in a facility that holds the write permission.
- A return list needs
patient_return=trueand adestination.
Notes
- Send
itemas an inventory item id. There is one inventory item per product per location. quantityanddays_supplytake whole numbers on write, though the columns store six decimal places.charge_itemis server-managed: Care creates it on create and cancels it with the dispense or its order.fully_dispensedsets the request'sdispense_status. Care does not check the request's status before a dispense.- The Care frontend's encounter Dispense drawer creates the order inline with its dispenses, then sends a separate update that sets the order to
completed.
Related
- Concept: Medication dispense
- Reference: Dispense order
- Reference: Medication request
- Reference: Medication administration
- Reference: Medication statement
- Reference: Inventory item
- Concept: Supply delivery
- Reference: Charge item
- Reference: Location
- Reference: Encounter
- Reference: Base model
- FHIR: MedicationDispense
- Source: medication_dispense.py · dispense/spec.py · viewsets/medication_dispense.py