# `mopidy.models` — Data models

These immutable data models are used for all data transfer within the Mopidy backends and between the backends and the MPD frontend. All fields are optional and immutable. In other words, they can only be set through the class constructor during instance creation. Additionally fields are type checked.

If you want to modify a model, use the `replace()` method. It accepts keyword arguments for the parts of the model you want to change, and copies the rest of the data from the model you call it on. Example:

    >>> from mopidy.models import Track
    >>> track1 = Track(name='Christmas Carol', length=171)
    >>> track1
    Track(artists=[], length=171, name='Christmas Carol')
    >>> track2 = track1.replace(length=37)
    >>> track2
    Track(artists=[], length=37, name='Christmas Carol')
    >>> track1
    Track(artists=[], length=171, name='Christmas Carol')

## Data model relations

digraph model_relations { Ref -> Album [ style="dotted", weight=1 ] Ref -> Artist [ style="dotted", weight=1 ] Ref -> Directory [ style="dotted", weight=1 ] Ref -> Playlist [ style="dotted", weight=1 ] Ref -> Track [ style="dotted", weight=1 ] Playlist -> Track [ label="has 0..n", weight=2 ] Track -> Album [ label="has 0..1", weight=10 ] Track -> Artist [ label="has 0..n", weight=10 ] Album -> Artist [ label="has 0..n", weight=10 ] Image SearchResult -> Artist [ label="has 0..n", weight=1 ] SearchResult -> Album [ label="has 0..n", weight=1 ] SearchResult -> Track [ label="has 0..n", weight=1 ] TlTrack -> Track [ label="has 1", weight=20 ] }

## Data model API

class mopidy.models.Ref(*args: Any, **kwargs: Any)

  Model to represent URI references with a human friendly name and type attached. This is intended for use a lightweight object “free” of metadata that can be passed around instead of using full blown models.

  Parameters:

    - uri (string) – object URI

    - name (string) – object name

    - type (string) – object type

  ALBUM = 'album'

    Constant used for comparison with the `type` field.

  ARTIST = 'artist'

    Constant used for comparison with the `type` field.

  DIRECTORY = 'directory'

    Constant used for comparison with the `type` field.

  PLAYLIST = 'playlist'

    Constant used for comparison with the `type` field.

  TRACK = 'track'

    Constant used for comparison with the `type` field.

  classmethod album(**kwargs)

    Create a `Ref` with `type` `ALBUM`.

  classmethod artist(**kwargs)

    Create a `Ref` with `type` `ARTIST`.

  classmethod directory(**kwargs)

    Create a `Ref` with `type` `DIRECTORY`.

  name

    The object name. Read-only.

  classmethod playlist(**kwargs)

    Create a `Ref` with `type` `PLAYLIST`.

  classmethod track(**kwargs)

    Create a `Ref` with `type` `TRACK`.

  type

    The object type, e.g. “artist”, “album”, “track”, “playlist”, “directory”. Read-only.

  uri

    The object URI. Read-only.

class mopidy.models.Track(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – track URI

    - name (string) – track name

    - artists (list of `Artist`) – track artists

    - album (`Album`) – track album

    - composers (list of `Artist`) – track composers

    - performers (list of `Artist`) – track performers

    - genre (string) – track genre

    - track_no (integer or `None` if unknown) – track number in album

    - disc_no (integer or `None` if unknown) – disc number in album

    - date (string) – track release date (YYYY or YYYY-MM-DD)

    - length (integer or `None` if there is no duration) – track length in milliseconds

    - bitrate (integer) – bitrate in kbit/s

    - comment (string) – track comment

    - musicbrainz_id (string) – MusicBrainz ID

    - last_modified (integer or `None` if unknown) – Represents last modification time

  album

    The track `Album`. Read-only.

  artists

    A set of track artists. Read-only.

  bitrate

    The track’s bitrate in kbit/s. Read-only.

  comment

    The track comment. Read-only.

  composers

    A set of track composers. Read-only.

  date

    The track release date. Read-only.

  disc_no

    The disc number in the album. Read-only.

  genre

    The track genre. Read-only.

  last_modified

    Integer representing when the track was last modified. Exact meaning depends on source of track. For local files this is the modification time in milliseconds since Unix epoch. For other backends it could be an equivalent timestamp or simply a version counter.

  length

    The track length in milliseconds. Read-only.

  musicbrainz_id

    The MusicBrainz ID of the track. Read-only.

  name

    The track name. Read-only.

  performers

    A set of track performers`. Read-only.

  track_no

    The track number in the album. Read-only.

  uri

    The track URI. Read-only.

class mopidy.models.Album(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – album URI

    - name (string) – album name

    - artists (list of `Artist`) – album artists

    - num_tracks (integer or `None` if unknown) – number of tracks in album

    - num_discs (integer or `None` if unknown) – number of discs in album

    - date (string) – album release date (YYYY or YYYY-MM-DD)

    - musicbrainz_id (string) – MusicBrainz ID

  artists

    A set of album artists. Read-only.

  date

    The album release date. Read-only.

  musicbrainz_id

    The MusicBrainz ID of the album. Read-only.

  name

    The album name. Read-only.

  num_discs

    The number of discs in the album. Read-only.

  num_tracks

    The number of tracks in the album. Read-only.

  uri

    The album URI. Read-only.

class mopidy.models.Artist(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – artist URI

    - name (string) – artist name

    - sortname (string) – artist name for sorting

    - musicbrainz_id (string) – MusicBrainz ID

  musicbrainz_id

    The MusicBrainz ID of the artist. Read-only.

  name

    The artist name. Read-only.

  sortname

    Artist name for better sorting, e.g. with articles stripped

  uri

    The artist URI. Read-only.

class mopidy.models.Playlist(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – playlist URI

    - name (string) – playlist name

    - tracks (list of `Track` elements) – playlist’s tracks

    - last_modified (int) – playlist’s modification time in milliseconds since Unix epoch

  last_modified

    The playlist modification time in milliseconds since Unix epoch. Read-only.

    Integer, or `None` if unknown.

  property length

    The number of tracks in the playlist. Read-only.

  name

    The playlist name. Read-only.

  tracks

    The playlist’s tracks. Read-only.

  uri

    The playlist URI. Read-only.

class mopidy.models.Image(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – URI of the image

    - width (int) – Optional width of image or `None`

    - height (int) – Optional height of image or `None`

  height

    Optional height of the image or `None`. Read-only.

  uri

    The image URI. Read-only.

  width

    Optional width of the image or `None`. Read-only.

class mopidy.models.TlTrack(*args: Any, **kwargs: Any)

  A tracklist track. Wraps a regular track and it’s tracklist ID.

  The use of `TlTrack` allows the same track to appear multiple times in the tracklist.

  This class also accepts it’s parameters as positional arguments. Both arguments must be provided, and they must appear in the order they are listed here.

  This class also supports iteration, so your extract its values like this:

      (tlid, track) = tl_track

  Parameters:

    - tlid (int) – tracklist ID

    - track (`Track`) – the track

  tlid

    The tracklist ID. Read-only.

  track

    The track. Read-only.

class mopidy.models.SearchResult(*args: Any, **kwargs: Any)
  Parameters:

    - uri (string) – search result URI

    - tracks (list of `Track` elements) – matching tracks

    - artists (list of `Artist` elements) – matching artists

    - albums (list of `Album` elements) – matching albums

  albums

    The albums matching the search query. Read-only.

  artists

    The artists matching the search query. Read-only.

  tracks

    The tracks matching the search query. Read-only.

  uri

    The search result URI. Read-only.

## Data model helpers

class mopidy.models.ValidatedImmutableObject(*args: Any, **kwargs: Any)

  Superclass for immutable objects whose fields can only be modified via the constructor. Fields should be `Field` instances to ensure type safety in our models.

  Note that since these models can not be changed, we heavily memoize them to save memory. So constructing a class with the same arguments twice will give you the same instance twice.

  replace(**kwargs)

    Replace the fields in the model and return a new instance.

    Examples:

        # Returns a track with a new name
        Track(name='foo').replace(name='bar')
        # Return an album with a new number of tracks
        Album(num_tracks=2).replace(num_tracks=5)

    Note that internally we memoize heavily to keep memory usage down given our overly repetitive data structures. So you might get an existing instance if it contains the same values.

    Parameters:

      kwargs (any) – kwargs to set as fields on the object

    Return type:

      instance of the model with replaced fields

### Data model (de)serialization

mopidy.models.model_json_decoder(dct)

  Automatically deserialize Mopidy models from JSON.

  Usage:

      >>> import json
      >>> json.loads(
      ...     '{"a_track": {"__model__": "Track", "name": "name"}}',
      ...     object_hook=model_json_decoder)
      {u'a_track': Track(artists=[], name=u'name')}

class mopidy.models.ModelJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

  Automatically serialize Mopidy models to JSON.

  Usage:

      >>> import json
      >>> json.dumps({'a_track': Track(name='name')}, cls=ModelJSONEncoder)
      '{"a_track": {"__model__": "Track", "name": "name"}}'

### Data model field types

class mopidy.models.fields.Field(default=None, type=None, choices=None) → None

  Base field for use in `ValidatedImmutableObject`. These fields are responsible for type checking and other data sanitation in our models.

  For simplicity fields use the Python descriptor protocol to store the values in the instance dictionary. Also note that fields are mutable if the object they are attached to allow it.

  Default values will be validated with the exception of `None`.

  Parameters:

    - default (`Optional`[`TypeVar`(`T`)]) – default value for field

    - type (`type`[`TypeVar`(`T`)] | `None`) – if set the field value must be of this type

    - choices (`Iterable`[`TypeVar`(`T`)] | `None`) – if set the field value must be one of these

class mopidy.models.fields.String(default=None) → None

  Specialized `Field` which is wired up for bytes and unicode.

  Parameters:

    default (`str` | `None`) – default value for field

class mopidy.models.fields.Identifier(default=None) → None

  `Field` for storing values such as GUIDs or other identifiers.

  Values will be interned.

  Parameters:

    default (`str` | `None`) – default value for field

class mopidy.models.fields.URI(default=None, type=None, choices=None) → None

  `Field` for storing URIs.

  Values will be interned, currently not validated.

  Parameters:

    default (`Optional`[`TypeVar`(`T`)]) – default value for field

class mopidy.models.fields.Date(default=None) → None

  `Field` for storing ISO 8601 dates as a string.

  Supported formats are `YYYY-MM-DD`, `YYYY-MM` and `YYYY`, currently not validated.

  Parameters:

    default (`str` | `None`) – default value for field

class mopidy.models.fields.Integer(default=None, min=None, max=None) → None

  `Field` for storing integer numbers.

  Parameters:

    - default – default value for field

    - min – field value must be larger or equal to this value when set

    - max – field value must be smaller or equal to this value when set

class mopidy.models.fields.Collection(type, container=<class 'tuple'>) → None

  `Field` for storing collections of a given type.

  Parameters:

    - type (`type`) – all items stored in the collection must be of this type

    - container (`Callable`[[], `tuple` | `frozenset`]) – the type to store the items in