Models

Module contents

Creates Model subclasses to represent the various DICOM entities.

../_images/models.png

Submodules

django_dicom.models.data_element module

Definition of the DataElement class.

class django_dicom.models.data_element.DataElement(*args, **kwargs)

Bases: django.db.models.base.Model

A model representing a single DICOM data element.

Each DataElement instance belongs to a Header, and each Header belongs to an Image or SequenceOfItems.

While the DataElement instance holds the reference to the associated models, the defining characteristics of the data element are saved as a DataElementDefinition instance and the values are saved as DataElementValue subclass instances in order to prevent data duplication.

Returns an HTML tag linking to this instance in the admin site.

Returns:HTML link to this instance
Return type:str
definition

The DataElementDefinition # noqa: E501 instance holding information about this element’s DICOM tag.

header

The Header instance to which this data element belongs.

objects = <django_dicom.models.managers.data_element.DataElementManager object>
to_html(**kwargs) → str

Returns an HTML representation of this instance.

Any keyword arguments will be passed to the associated DataElementValue subclass instances.

Returns:HTML representaion of this instance
Return type:str
to_verbose_dict() → dict

Returns a dictionary representation of this instance.

Returns:This instance’s information
Return type:dict
to_verbose_series() → pandas.core.series.Series

Returns a Series representation of this instance.

Returns:This instance’s information
Return type:pandas.Series
value

Returns the value or values (according to the value multiplicity) of the associated DataElementValue instances.

Returns:Data element value
Return type:Any
value_multiplicity

Returns the number of DataElementValue related to this instance.

Returns:Value multiplicity
Return type:int

Hint

For more information see the DICOM standard’s definition of value multiplicity.

django_dicom.models.data_element_definition module

Definition of the DataElementDefinition class.

class django_dicom.models.data_element_definition.DataElementDefinition(*args, **kwargs)

Bases: django.db.models.base.Model

A model representing a single DICOM data element definition.

Notes

For more information see the DICOM standard’s documentation as well as registry of data elements.

Returns an HTML tag linking to this instance in the admin site.

Returns:HTML link to this instance
Return type:str
data_element_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

description

A short description of this data element.

get_value_representation_display(*, field=<django.db.models.fields.CharField: value_representation>)
keyword

Most data elements have some keyword that facilitates querying header information.

objects = <django_dicom.models.managers.data_element_definition.DataElementDefinitionManager object>
tag

Data element tags are an ordered pair of 16-bit unsigned integers representing the Group Number followed by Element Number and they are represented in the database using an array (list) of two four character strings.

to_dict() → dict

Returns a dictionary representation of this instance.

Returns:This instance’s dictionary representation
Return type:dict
to_series() → pandas.core.series.Series

Returns a Series representation of this instance.

Returns:Series representation of this instance
Return type:pandas.Series
value_representation

The value representation (VR) defines the type of information stored in the data element. This will be used to determine which DataElementValue subclass is instantiated to save this information to the database.

django_dicom.models.dicom_entity module

Definition of the DicomEntity class. This abstract model serves as a base class for the various DICOM entities (e.g. Study and Patient).

class django_dicom.models.dicom_entity.DicomEntity(*args, **kwargs)

Bases: django_extensions.db.models.TimeStampedModel

Abstract model providing common functionality for DICOM entities. For more information about DICOM entites, see this introduction.

FIELD_TO_HEADER = {}

A dictionary used to convert field names to header keywords.

class Meta

Bases: object

abstract = False

Calls get_admin_link() to return a link to this instance’s page in the admin site.

Returns:HTML element
Return type:str

Returns an HTML link to this instance’s page in the admin site.

Parameters:text (str, optional) – Text to display, by default None
Returns:HTML element
Return type:str
get_header_fields() → list

Returns a list of the derived model’s fields which represent DICOM header information.

Returns:Fields representing DICOM header information
Return type:list
classmethod get_header_keyword(field_name: str) → str

Returns the data element keyword to return the requested field’s value from header data. Relies on the derived model’s FIELD_TO_HEADER class attribute. If no matching key is found, will simply return the field’s name in CamelCase formatting (the formatting of pydicom’s header keywords).

Returns:pydicom header keyword
Return type:str
is_header_field(field: django.db.models.fields.Field) → bool

Returns a boolean indicating whether the provided field represents DICOM header information or not.

Parameters:field (Field) – Field in question
Returns:Whether this field represent DICOM header information or not
Return type:bool
log_creation() → None

Logs the creation of a new instance of the calling Entity.

objects
save(*args, **kwargs)

Overrides save() to create logs and update the instance’s fields from header information if provided.

update_fields_from_header(header, exclude: list = None) → None

Update fields from header data.

Parameters:

django_dicom.models.header module

Definition of the Header class.

class django_dicom.models.header.Header(*args, **kwargs)

Bases: model_utils.models.TimeStampedModel

A model representing a single DICOM Data Set.

Creates an HTML tag to link to this instance within the admin site.

Returns:Link to this instance in the admin site
Return type:str
data_element_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

get_entity_uid(entity: django_dicom.models.dicom_entity.DicomEntity) → str

Returns the UID of the provided DICOM entity from the header information.

Parameters:entity (DicomEntity) – The entity for which a UID is desired
Returns:The provided DICOM entity’s unique identifier
Return type:str
get_or_create_entity(entity: django_dicom.models.dicom_entity.DicomEntity) → tuple

Get or create a DICOM entity’s instance from this header.

Parameters:entity (DicomEntity) – The desired DICOM entity’s model
Returns:instance, creatd
Return type:tuple
get_or_create_patient() → tuple

Get or create the Patient instance corresponding to this header.

Returns:instance, created
Return type:tuple
get_or_create_series() → tuple

Get or create the Series instance corresponding to this header.

Returns:instance, created
Return type:tuple
get_or_create_study() → tuple

Get or create the Study instance corresponding to this header.

Returns:instance, created
Return type:tuple
get_value_by_keyword(keyword: str) → Any

Returns a data element’s value by keyword from the database (not from the DICOM header itself, ergo only elements that are saved to the database may be queried).

Parameters:keyword (str) – Data element keyword
Returns:Data element value
Return type:Any
image

Accessor to the related object on the reverse side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

index

This Data Set’s index in the sequence (if parent is not None).

instance

Caches the created dicom_parser.header.Header instance to prevent multiple reades.

Returns:Header information
Return type:dicom_parser.header.Header
objects = <django_dicom.models.managers.header.HeaderManager object>
parent

Data Set <http://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html>`_s `may be nested. If this header (Data Set) is an item of some sequence, this field holds that reference.

to_html(verbose: bool = False, **kwargs) → str

Returns an HTML representation of this instance.

Parameters:verbose (bool, optional) – Whether to return a JSON with all of the header information or just a link to this instance’s admin page, by default False.
Returns:HTML representaion of this instance
Return type:str
to_verbose_list() → List[dict]

Returns a list of dictionaries containing the information from the data elements in this header.

Returns:Header information as a list of dictionaries
Return type:List[dict]

django_dicom.models.image module

Definition of the Image class.

class django_dicom.models.image.Image(*args, **kwargs)

Bases: django_dicom.models.dicom_entity.DicomEntity

A model to represent a single instance of the Image entity. This model is normally instantiated with the dcm field set to some .dcm file from which the header information is read.

FIELD_TO_HEADER = {'date': 'InstanceCreationDate', 'number': 'InstanceNumber', 'time': 'InstanceCreationTime', 'uid': 'SOPInstanceUID'}

A dictionary of DICOM data element keywords to be used to populate a created instance’s fields.

create_header_instance() → django_dicom.models.header.Header

Creates a Header instance from a dicom_parser.header.Header.

Returns:Created instance
Return type:Header
data

Facilitates access to the Image instance’s data.

Returns:The image’s pixel data
Return type:np.ndarray
date

Instance Creation Date value.

dcm

A reference to the DICOM image file.

default_path

Default unique path for this image based on its header information.

Returns:Default image location
Return type:pathlib.Path
get_absolute_url() → str

Returns the absolute URL for this instance. For more information see the Django documentation.

Returns:This instance’s absolute URL path
Return type:str
get_default_path() → pathlib.Path

Returns a unique default path under MEDIA_ROOT for this instance based on its header information.

Returns:This instance’s default location
Return type:pathlib.Path
header

The associated Header instance representing this image’s header information.

instance

Caches the created dicom_parser.image.Image instance to prevent multiple reads.

Returns:Image information
Return type:dicom_parser.image.Image
logger = <Logger data.dicom.image (WARNING)>
number

Instance Number value.

objects = <django_dicom.models.managers.image.ImageManager object>
patient

Returns the Patient associated with this image.

Returns:Associated Patient instance
Return type:Patient
rename(target: pathlib.Path) → None

Move the .dcm file this instance references to some target destination.

Parameters:target (pathlib.Path) – Destination path
save(*args, rename: bool = True, **kwargs)

Overrides save() to check for missing header information or associated DICOM entities and create them if a .dcm file is provided.

Parameters:rename (bool, optional) – Whether to move the file this instance is a reference to to a default path under MEDIA_ROOT or not, by default True
sequence_type

Returns the MRI sequence type detected by dicom_parser.

Returns:Sequence type identifier
Return type:str
series

The Series instance to which this image belongs.

time

Instance Creation Time value.

uid

SOP Instance UID value.

warnings

In case any warnings are raised by dicom_parser upon reading the image’s header information, they are stored in this field.

django_dicom.models.patient module

Definition of the Patient class.

class django_dicom.models.patient.Patient(*args, **kwargs)

Bases: django_dicom.models.dicom_entity.DicomEntity

A model to represent a single instance of the Patient entity.

FIELD_TO_HEADER = {'date_of_birth': 'PatientBirthDate', 'sex': 'PatientSex', 'uid': 'PatientID'}

A dictionary of DICOM data element keywords to be used to populate a created instance’s fields.

date_of_birth

Patient Birth Date value.

family_name

Patient’s Name value.

get_absolute_url() → str

Returns the absolute URL for this instance.

Returns:This instance’s absolute URL path
Return type:str
get_full_name() → str

Returns the first and last names of the patient.

Returns:Patient’s first and last names.
Return type:str
get_sex_display(*, field=<django.db.models.fields.CharField: sex>)
given_name

Patient’s Name value.

logger = <Logger data.dicom.patient (WARNING)>
middle_name

Patient’s Name value.

n_images

Returns the number of associated images.

See also

Returns:Number of associated images
Return type:int
n_series

Returns the number of associated series.

Returns:Number of associated series
Return type:int
n_studies

Returns the number of associated studies.

Returns:Number of associated studies
Return type:int
name_prefix

Patient’s Name value.

name_suffix

Patient’s Name value.

objects = <django.db.models.manager.DicomEntityManagerFromPatientQuerySet object>
query_n_images() → int

Returns the number of associated images.

See also

n_images()

Returns:Number of associated images
Return type:int
query_n_studies() → int

Returns the number of associated studies.

See also

n_studies()

Returns:Number of associated studies
Return type:int
query_research_subject()

Returns the associated research subject, if such a model is registered and a matching instance exists.

Returns:Associated research subject
Return type:Subject
research_subject

Returns the associated research subject, if such a model is registered and a matching instance exists.

Returns:Associated research subject
Return type:Subject
series_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

sex

Patient’s Sex value.

uid

Patient ID value.

update_fields_from_header(header, exclude: list = None) → None

Overrides update_fields_from_header() to handle setting the name parts.

Parameters:
  • header (Header) – DICOM header information.
  • exclude (list, optional) – Field names to exclude (the default is [], which will not exclude any header fields).
update_patient_name(header) → None

Parses the patient’s name from the DICOM header and updates the instance’s fields.

Parameters:header (Header) – A DICOM image’s Header instance.

django_dicom.models.series module

Definition of the Series class.

class django_dicom.models.series.Series(*args, **kwargs)

Bases: django_dicom.models.dicom_entity.DicomEntity

A model to represent a single instance of the Series entity.

FIELD_TO_HEADER = {'date': 'SeriesDate', 'description': 'SeriesDescription', 'mr_acquisition_type': 'MRAcquisitionType', 'number': 'SeriesNumber', 'pulse_sequence_name': (25, 4252), 'time': 'SeriesTime', 'uid': 'SeriesInstanceUID'}

A dictionary of DICOM data element keywords to be used to populate a created instance’s fields.

MR_ACQUISITION_2D = '2D'

MR Acquisition Type value.

MR_ACQUISITION_3D = '3D'
MR_ACQUISITION_TYPE_CHOICES = (('2D', '2D'), ('3D', '3D'))
body_part_examined

Body Part Examined value.

data

Returns the dicom_parser.series.Series.data property’s value.

Returns:Series data
Return type:np.ndarray
date

Series Date value.

datetime

Returns a datetime.datetime object by combining the values of the date and time fields.

Returns:Series datetime
Return type:datetime.datetime
description

Series Description value.

device_serial_number

Device Serial Number value.

echo_time

Echo Time value.

echo_train_length

Echo Train Length value.

flip_angle

Flip Angle value.

get_absolute_url() → str

Returns the absolute URL for this instance. For more information see the Django documentation.

Returns:This instance’s absolute URL path
Return type:str
get_file_paths() → Tuple[pathlib.Path]
get_modality_display(*, field=<django.db.models.fields.CharField: modality>)
get_mr_acquisition_type_display(*, field=<django.db.models.fields.CharField: mr_acquisition_type>)
get_path() → pathlib.Path

Returns the base directory containing the images composing this series.

Returns:This series’s base directory path
Return type:str
get_patient_position_display(*, field=<django.db.models.fields.CharField: patient_position>)
get_sample_header() → dicom_parser.header.Header

Return a sample Header instance for this series.

See also

Returns:Sample image header information
Return type:DicomHeader
get_scanning_sequence_display() → list

Returns the display valuse of this instance’s scanning_sequence attribute.

Returns:Verbose scanning sequence values
Return type:list
get_sequence_type_display(*, field=<django.db.models.fields.CharField: sequence_type>)
get_sequence_variant_display() → list

Returns the display valuse of this instance’s sequence_variant attribute.

Returns:Verbose sequence variant values
Return type:list
image_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

instance

Caches the created dicom_parser.series.Series instance to prevent multiple reades.

Returns:Series information
Return type:dicom_parser.series.Series
institution_name

Institution Name value.

inversion_time

Inversion Time value.

logger = <Logger data.dicom.series (WARNING)>
magnetic_field_strength

Magnetic Field Strength value.

manufacturer

Manufacturer value.

manufacturer_model_name

Manufacturer’s Model Name value.

missing_relation

Returns whether this instance misses an associated Patient or Study.

Returns:Whether this instance has missing relationships
Return type:bool
modality

Modality value.

mr_acquisition_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

number

Series Number value.

operators_name

Operator’s Name value.

path

Returns the base path of this series’ images.

Returns:Series directory path
Return type:pathlib.Path
patient

The Patient instance to which this series belongs.

patient_position

Patient Position value.

pixel_spacing

Pixel Spacing value.

protocol_name

Protocol Name value.

pulse_sequence_name

Pulse Sequence Name value.

repetition_time

Repetition Time value.

sample_header

Return a sample Header instance for this series.

Returns:Sample image header information
Return type:DicomHeader
save(*args, **kwargs) → None

Overrides save() to create any missing related DICOM entities if required.

scanning_sequence

Scanning Sequence value.

sequence_name

Sequence Name value.

sequence_type

Scanning sequence type identifier, as detected by dicom_parser.

sequence_variant

Sequence Variant value.

slice_thickness

Slice Thickness value.

spatial_resolution

Returns the 3D spatial resolution of the instance by combining the values of the pixel_spacing and slice_thickness fields.

Returns:(x, y, z) resolution in millimeters
Return type:tuple
study

The Study instance to which this series belongs.

time

Series Time value.

uid

Series Instance UID value.

update_sequence_type(save: bool = True)

Checks the sequence type identifier detected by dicom_parser and updates the serialized value if required.

Parameters:save (bool) – Whether to save changes or not, default is True

django_dicom.models.study module

Definition of the Study class.

class django_dicom.models.study.Study(*args, **kwargs)

Bases: django_dicom.models.dicom_entity.DicomEntity

A model to represent a single instance of the Study entity.

FIELD_TO_HEADER = {'date': 'StudyDate', 'description': 'StudyDescription', 'time': 'StudyTime', 'uid': 'StudyInstanceUID'}

A dictionary of DICOM data element keywords to be used to populate a created instance’s fields.

date

Study Date value.

description

Study Description value.

get_absolute_url()

Returns the absolute URL for this instance. For more information see the Django documentation.

Returns:This instance’s absolute URL path
Return type:str
logger = <Logger data.dicom.study (WARNING)>
n_images

Returns the number of associated images.

See also

query_n_images()

Returns:Number of associated images
Return type:int
n_patients

Returns the number of associated patients.

Returns:Number of associated patients
Return type:int
n_series

Returns the number of associated series.

Returns:Number of associated series
Return type:int
objects = <django.db.models.manager.DicomEntityManagerFromStudyQuerySet object>
query_n_images() → int

Returns the number of associated images.

See also

n_images()

Returns:Number of associated images
Return type:int
query_n_patients() → int

Returns the number of associated patients.

See also

n_patients()

Returns:Number of associated patients
Return type:int
series_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

time

Study Time value.

uid

Study Instance UID value.