Skip to main content
Version: 3.1

Product Knowledge

Technical reference for the ProductKnowledge module in Care EMR. For what Product Knowledge means to facility users, see the Product Knowledge concept.

ProductKnowledge is the reusable definition of a product: its coding, base unit, names, storage guidelines, and type-specific definition. Every Product references one ProductKnowledge record. A record is either instance-level (no facility) or scoped to one facility.

The Django model is only the storage layer: code, names, storage_guidelines, definitional, and base_unit are JSONFields whose structure lives in the Pydantic resource specs. The enums, nested shapes, and validation below come from those specs; the endpoints, scoping, and authorization come from the viewset.

Source:

Models​

ModelPurpose
ProductKnowledgeReusable definition of a product (medication, nutritional product, or consumable)

ProductKnowledge extends SlugBaseModel, which extends EMRBaseModel. The shared base provides external_id, created_date, modified_date, and soft delete through deleted; EMRBaseModel adds created_by, updated_by, history, and meta.

SlugBaseModel sets FACILITY_SCOPED = True and adds the slug helpers calculate_slug_from_facility, calculate_slug_from_instance, and parse_slug. It defines no save(): the viewset prefixes the slug on create and update (see Slug prefixing).

ProductKnowledge fields​

Identity & scope​

FieldTypeNotes
facilityFK → facility.FacilityPROTECT, nullable. Null means instance-level; set means facility-scoped. In the spec base's __exclude__; only ProductKnowledgeWriteSpec (create) sets it, so an update cannot move a record to another facility. Surfaced on read as is_instance_level
slugCharField(255)Stores the full prefixed slug: f-<facility external_id>-<slug_value> or i-<slug_value>. The viewset sets it from slug_value on create and update. The API's lookup field
alternate_identifierCharField(255), nullableSecondary identifier. The UI labels it "HSN Code"
statusCharField(255)Spec-constrained to ProductKnowledgeStatusOptions (required)
product_typeCharField(255)Spec-constrained to ProductTypeOptions (required)
categoryFK → emr.ResourceCategoryPROTECT, nullable. Classifies the record into a resource category. Written as a category slug string; read returns the serialized category

Naming​

FieldTypeNotes
nameCharField(255)Primary display name (required in spec)
namesJSONField (list), nullablelist[ProductName] | None. See ProductName
names_cacheCharField(2048), nullablename plus every names[].name, space-joined, rebuilt on each save() by set_names_cache(). Searched by the alternate_names filter. In no spec; never set it from clients

Coding & definition (JSON fields)​

The model stores these as nullable JSONFields; the spec enforces the shapes below.

FieldModel typeSpec type / shapeNotes
codeJSONField (dict)Coding | NoneOptional product code as a Coding; not value-set bound at the spec layer. The UI searches system-medication for it
base_unitJSONField (dict)ValueSetBoundCoding[CARE_UCUM_UNITS]Required. Bound to the UCUM units value set (system-ucum-units). The UI offers a fixed list of eight units
namesJSONField (list)list[ProductName] | NoneSee ProductName
storage_guidelinesJSONField (list)list[StorageGuideline] | NoneSee StorageGuideline
definitionalJSONField (dict)ProductDefinitionSpec | NoneSee ProductDefinitionSpec. The spec does not tie its contents to product_type

Enums​

ProductTypeOptions (product_type)​

ValueUI label
medicationMedication
nutritional_productNutritional Product
consumableNone: the locale files have no consumable key, so the UI shows the raw word "consumable"

ProductKnowledgeStatusOptions (status)​

ValueNotes
draftOffered by the UI form as "Draft"
activeOffered by the UI form as "Active"; the UI's default for new records. The UI's product knowledge pickers list only active records
retiredOffered by the UI form as "Retired"; set by the UI's "Delete" action
unknownAccepted by the API; the UI form does not offer it

ProductNameTypes (names[].name_type)​

ValueUI label
trade_nameTrade Name (the UI's default)
aliasAlias
original_nameOriginal Name
preferredPreferred

DrugCharacteristicCode (definitional.drug_characteristic[].code)​

API only: the UI form has no field for drug characteristics.

Value
imprint_code
size
shape
color
coating
scoring
logo
image

Nested spec shapes​

These are plain Pydantic BaseModels in spec.py. Every field listed as required has no default.

ProductName​

names[]: alternate names for the product.

FieldTypeRequiredNotes
name_typeProductNameTypesyesEnum, see above
namestryes

StorageGuideline​

storage_guidelines[]: a storage note paired with a stability duration.

FieldTypeRequiredNotes
notestryes
stability_durationDurationSpec = value: int, unit: Codingyesvalue is a whole number; unit is a free Coding. The UI offers minutes, hours, days, weeks, months, and years

ProductDefinitionSpec​

definitional: the dosage form, routes, ingredients, nutrients, and drug characteristics. The 3.1 UI form edits only dosage_form and intended_routes; the other three lists are set through the API only.

FieldTypeDefaultNotes
dosage_formValueSetBoundCoding[MEDICATION_FORM_CODES] | Nonerequired (nullable)Bound to medication form codes (system-medication-form-codes, SNOMED is-a 736542009)
intended_routeslist[Coding][]Free Codings, not value-set bound. The UI picks them from system-route
ingredientslist[ProductIngredient][]See ProductIngredient
nutrientslist[ProductNutrient][]See ProductNutrient
drug_characteristiclist[DrugCharacteristic][]See DrugCharacteristic

ProductIngredient​

definitional.ingredients[].

FieldTypeRequiredNotes
is_activeboolyesActive or inactive ingredient
substanceValueSetBoundCoding[CARE_SUBSTANCE_VALUSET]yesBound to the substance value set (system-substance, SNOMED is-a 105590001)
strengthProductStrengthyesSee ProductStrength

ProductNutrient​

definitional.nutrients[].

FieldTypeRequiredNotes
itemValueSetBoundCoding[CARE_NUTRIENTS_VALUESET]yesBound to the nutrients value set (system-nutrients, SNOMED is-a 226355009)
amountProductStrengthyesSee ProductStrength

ProductStrength​

Shared by ProductIngredient.strength and ProductNutrient.amount.

FieldTypeRequiredNotes
ratioRatio = numerator: Quantity, denominator: Quantityyes
quantityQuantityyesSee Quantity

DrugCharacteristic​

definitional.drug_characteristic[].

FieldTypeRequiredNotes
codeDrugCharacteristicCodeyesEnum, see above
valuestryes

Shared common types​

Coding​

From care/emr/resources/common/coding.py (extra="forbid").

FieldTypeRequired
systemstr | Noneno
versionstr | Noneno
codestryes
displaystr | Noneno

A ValueSetBoundCoding[<slug>] is a Coding whose code is validated against the named value set on input.

Quantity​

From care/emr/resources/common/quantity.py (extra="forbid").

FieldTypeNotes
valueDecimal | NoneAt most 20 digits, 6 decimal places
unitCoding | NoneHuman-readable form of the unit
codeCoding | NoneComputer-processable form of the unit
metadict | None

Ratio has numerator: Quantity and denominator: Quantity, both required.

ModelFieldRelationship
Productproduct_knowledgeRequired FK to ProductKnowledge, PROTECT. Every product references one record
InventoryItemproductRequired FK to Product, PROTECT; reaches ProductKnowledge only through the product
SupplyRequestitemFK to ProductKnowledge, CASCADE
MedicationRequestrequested_productOptional FK to ProductKnowledge, SET_NULL
MedicationAdministrationadministered_productOptional FK to ProductKnowledge, CASCADE

Resource specs (API schema)​

Every spec builds on EMRResource (care/emr/resources/base.py).

Spec classRoleAdds / behaviour
BaseProductKnowledgeSpecshared base__exclude__ = ["facility"]. Fields: id, alternate_identifier, status, product_type, code, base_unit (required, UCUM-bound), name, names, storage_guidelines, definitional
ProductKnowledgeUpdateSpecwrite · updateAdds category: str | None (resource category slug) and slug_value: SlugType (required). On deserialize, resolves category with ResourceCategory.objects.get(slug=...) and sets obj.slug = slug_value
ProductKnowledgeWriteSpecwrite · createExtends the update spec; adds facility: UUID4 | None. On deserialize, runs the update-spec logic, then resolves facility by external id
ProductKnowledgeReadSpecread · list and detailAdds is_instance_level (true when there is no facility), category (serialized resource category), slug_config (the parsed slug: facility and slug_value, or slug_value only), and slug

Validation & bound value sets​

  • status, product_type, base_unit, and name are required.
  • base_unit is bound to system-ucum-units.
  • definitional.dosage_form is bound to system-medication-form-codes, ingredients[].substance to system-substance, and nutrients[].item to system-nutrients. code and intended_routes stay free Codings.
  • slug_value uses SlugType: 5–50 characters, starting and ending with a letter or digit, and containing only letters, digits, -, and _.
  • Create and update reject a slug that already exists in the same scope (the same facility, or instance level), compared without case, with the validation error "Slug already exists.".
  • For a facility record, the viewset returns 404 for an unknown category slug.

Server-maintained behaviour​

  • facility is set only on create, from ProductKnowledgeWriteSpec.facility.
  • The viewset prefixes slug on create and update; the model rebuilds names_cache in save().
  • is_instance_level, slug_config, and the serialized category are computed on read; none of them is a stored column.

Methods & save behaviour​

save() side effects​

save() calls set_names_cache() before it writes the record:

  1. names_cache is reset to "<name> ".
  2. The name of each entry in names is appended, separated by spaces.
  3. super().save() writes the record.

names_cache is platform-maintained: write name and names instead.

Slug prefixing​

ProductKnowledgeViewSet.recalculate_slug() runs in perform_create and perform_update. It stores f-<facility external_id>-<slug_value> for a facility record and i-<slug_value> for an instance-level record. SlugBaseModel has no save() of its own.

API integration notes​

Endpoints​

The API is registered at /api/v1/product_knowledge/, not nested under a facility. Records are addressed by slug, the full prefixed slug.

Method and pathActionNotes
GET /api/v1/product_knowledge/listSee filters and scoping below
POST /api/v1/product_knowledge/createBody: ProductKnowledgeWriteSpec
GET /api/v1/product_knowledge/<slug>/retrieveReturns ProductKnowledgeReadSpec
PUT /api/v1/product_knowledge/<slug>/updateBody: ProductKnowledgeUpdateSpec. The UI sends PUT
POST /api/v1/product_knowledge/upsert/upsertBody: a datapoints list. A datapoint with id (the slug) updates that record; one without id creates a record. If any datapoint fails, the batch is rolled back and the response is 400 with the per-datapoint results
GET /api/v1/product_knowledge/favorite_lists/favoritesThe caller's favorite list names
POST /api/v1/product_knowledge/<slug>/add_favorite/favoritesBody: optional favorite_list
POST /api/v1/product_knowledge/<slug>/remove_favorite/favoritesBody: optional favorite_list

There is no delete endpoint. The UI's "Delete" action sends a PUT that sets status to retired.

Filters and ordering​

ParameterBehaviour
facilityScopes the list to one facility. See scoping below
include_instanceWith facility: true adds instance-level records
categoryA category slug, looked up in the same facility. With include_children=true, records in descendant categories are also returned
status, product_type, alternate_identifierExact match, case-insensitive
name, alternate_namesTrigram similarity above 0.1 on name or names_cache, ordered by similarity
facility_is_nullNull filter on facility
orderingcreated_date or modified_date

Scoping and authorization​

  • List with facility: requires can_read_product_knowledge in any organization of that facility. Returns that facility's records, plus instance-level records when include_instance=true.
  • List without facility: returns only instance-level records, with no permission check.
  • Retrieve a facility record: requires can_read_product_knowledge in any organization of its facility; otherwise 403 "Cannot read product knowledge". Retrieving an instance-level record has no permission check.
  • Create a facility record: requires can_write_product_knowledge in the facility's root organization (named "Administration"); otherwise 403 "Cannot create product knowledge". A role holding the permission in another department of the facility is refused.
  • Update a facility record: requires can_write_product_knowledge in the root organization of the record's facility; otherwise 403 "Cannot update product knowledge".
  • Instance-level records cannot be created or updated through facility permissions.
  • Only facility-organization memberships count; governance-organization memberships are not consulted.
  • The frontend's list calls send include_instance=true by default, so pickers that do not override it also list instance-level records.
PermissionDisplay nameChecked inDefault roles
can_write_product_knowledgeCan Create Product Knowledge on FacilityThe facility's root organizationFacility Admin
can_read_product_knowledgeCan Read Product KnowledgeAny organization of the facilityFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist

Authorization reads role permissions from the database. Each permission sync rewrites the default roles from code; custom roles can also hold these permissions.

UI notes​

  • The UI labels alternate_identifier "HSN Code".
  • The UI creates records only inside a category with no subcategories, and always sends the current facility.
  • The 3.1 UI form has no fields for ingredients, nutrients, or drug_characteristic.
  • The UI's create form opens with the definitional block added, and requires dosage_form until the user removes the block.