django-timescaledb


Namedjango-timescaledb JSON
Version 0.2.13 PyPI version JSON
download
home_pagehttps://github.com/schlunsen/django-timescaledb
SummaryA Django database backend for integration with TimescaleDB
upload_time2023-02-07 13:15:57
maintainer
docs_urlNone
authorRasmus Schlünsen
requires_python
licenseApache-2.0 License
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Django timescaledb
==================

A database backend and tooling for Timescaledb.

Based on
`gist <https://gist.github.com/dedsm/fc74f04eb70d78459ff0847ef16f2e7a>`__
from WeRiot.

Quick start
-----------

1. Install via pip

.. code:: bash

    pip install django-timescaledb

2. Use as DATABASE engine in settings.py:

Standard PostgreSQL

.. code:: python

    DATABASES = {
        'default': {
            'ENGINE': 'timescale.db.backends.postgresql',
            ...
        },
    }

PostGIS

.. code:: python

    DATABASES = {
        'default': {
            'ENGINE': 'timescale.db.backends.postgis',
            ...
        },
    }

If you already make use of a custom PostgreSQL db backend you can set
the path in settings.py.

.. code:: python

    TIMESCALE_DB_BACKEND_BASE = "django.contrib.gis.db.backends.postgis"

3. Inherit from the TimescaleModel. A
   `hypertable <https://docs.timescale.com/latest/using-timescaledb/hypertables#react-docs>`__
   will automatically be created.

.. code:: python


      class TimescaleModel(models.Model):
        """
        A helper class for using Timescale within Django, has the TimescaleManager and 
        TimescaleDateTimeField already present. This is an abstract class it should 
        be inheritted by another class for use.
        """
        time = TimescaleDateTimeField(interval="1 day")

        objects = TimescaleManager()

        class Meta:
            abstract = True

Implementation would look like this

.. code:: python

    from timescale.db.models.models import TimescaleModel

    class Metric(TimescaleModel):
       temperature = models.FloatField()
       

If you already have a table, you can either add `time`
field of type `TimescaleDateTimeField` to your model or
rename (if not already named `time`) and change type of
existing `DateTimeField` (rename first then run
`makemigrations` and then change the type, so that
`makemigrations` considers it as change in same field
instead of removing and adding new field). This also
triggers the creation of a hypertable.

.. code:: python

    from timescale.db.models.fields import TimescaleDateTimeField
    from timescale.db.models.managers import TimescaleManager

    class Metric(models.Model):
      time = TimescaleDateTimeField(interval="1 day")

      objects = models.Manager()
      timescale = TimescaleManager()

The name of the field is important as Timescale specific feratures
require this as a property of their functions. ### Reading Data

"TimescaleDB hypertables are designed to behave in the same manner as
PostgreSQL database tables for reading data, using standard SQL
commands."

As such the use of the Django's ORM is perfectally suited to this type
of data. By leveraging a custom model manager and queryset we can extend
the queryset methods to include Timescale functions.

Time Bucket `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#time-bucket>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

      Metric.timescale.filter(time__range=date_range).time_bucket('time', '1 hour')

      # expected output

      <TimescaleQuerySet [{'bucket': datetime.datetime(2020, 12, 22, 11, 0, tzinfo=<UTC>)}, ... ]>

Time Bucket Gap Fill `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#gap-filling>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

      from metrics.models import *
      from django.db.models import Count, Avg
      from django.utils import timezone
      from datetime import timedelta

      ranges = (timezone.now() - timedelta(days=2), timezone.now())

      (Metric.timescale
        .filter(time__range=ranges)
        .time_bucket_gapfill('time', '1 day', ranges[0], ranges[1], datapoints=240)
        .annotate(Avg('temperature')))

      # expected output

      <TimescaleQuerySet [{'bucket': datetime.datetime(2020, 12, 21, 21, 24, tzinfo=<UTC>), 'temperature__avg': None}, ...]>

Histogram `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#histogram>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

      from metrics.models import *
      from django.db.models import Count
      from django.utils import timezone
      from datetime import timedelta

      ranges = (timezone.now() - timedelta(days=3), timezone.now())

      (Metric.timescale
        .filter(time__range=ranges)
        .values('device')
        .histogram(field='temperature', min_value=50.0, max_value=55.0, num_of_buckets=10)
        .annotate(Count('device')))
        
      # expected output

      <TimescaleQuerySet [{'histogram': [0, 0, 0, 87, 93, 125, 99, 59, 0, 0, 0, 0], 'device__count': 463}]>


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/schlunsen/django-timescaledb",
    "name": "django-timescaledb",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Rasmus Schl\u00fcnsen",
    "author_email": "raller84@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/85/9f/88107d46771b0236a80db0ab4324650b73973187141f214b24f46b7c4cf2/django-timescaledb-0.2.13.tar.gz",
    "platform": null,
    "description": "Django timescaledb\n==================\n\nA database backend and tooling for Timescaledb.\n\nBased on\n`gist <https://gist.github.com/dedsm/fc74f04eb70d78459ff0847ef16f2e7a>`__\nfrom WeRiot.\n\nQuick start\n-----------\n\n1. Install via pip\n\n.. code:: bash\n\n    pip install django-timescaledb\n\n2. Use as DATABASE engine in settings.py:\n\nStandard PostgreSQL\n\n.. code:: python\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'timescale.db.backends.postgresql',\n            ...\n        },\n    }\n\nPostGIS\n\n.. code:: python\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'timescale.db.backends.postgis',\n            ...\n        },\n    }\n\nIf you already make use of a custom PostgreSQL db backend you can set\nthe path in settings.py.\n\n.. code:: python\n\n    TIMESCALE_DB_BACKEND_BASE = \"django.contrib.gis.db.backends.postgis\"\n\n3. Inherit from the TimescaleModel. A\n   `hypertable <https://docs.timescale.com/latest/using-timescaledb/hypertables#react-docs>`__\n   will automatically be created.\n\n.. code:: python\n\n\n      class TimescaleModel(models.Model):\n        \"\"\"\n        A helper class for using Timescale within Django, has the TimescaleManager and \n        TimescaleDateTimeField already present. This is an abstract class it should \n        be inheritted by another class for use.\n        \"\"\"\n        time = TimescaleDateTimeField(interval=\"1 day\")\n\n        objects = TimescaleManager()\n\n        class Meta:\n            abstract = True\n\nImplementation would look like this\n\n.. code:: python\n\n    from timescale.db.models.models import TimescaleModel\n\n    class Metric(TimescaleModel):\n       temperature = models.FloatField()\n       \n\nIf you already have a table, you can either add `time`\nfield of type `TimescaleDateTimeField` to your model or\nrename (if not already named `time`) and change type of\nexisting `DateTimeField` (rename first then run\n`makemigrations` and then change the type, so that\n`makemigrations` considers it as change in same field\ninstead of removing and adding new field). This also\ntriggers the creation of a hypertable.\n\n.. code:: python\n\n    from timescale.db.models.fields import TimescaleDateTimeField\n    from timescale.db.models.managers import TimescaleManager\n\n    class Metric(models.Model):\n      time = TimescaleDateTimeField(interval=\"1 day\")\n\n      objects = models.Manager()\n      timescale = TimescaleManager()\n\nThe name of the field is important as Timescale specific feratures\nrequire this as a property of their functions. ### Reading Data\n\n\"TimescaleDB hypertables are designed to behave in the same manner as\nPostgreSQL database tables for reading data, using standard SQL\ncommands.\"\n\nAs such the use of the Django's ORM is perfectally suited to this type\nof data. By leveraging a custom model manager and queryset we can extend\nthe queryset methods to include Timescale functions.\n\nTime Bucket `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#time-bucket>`__\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n      Metric.timescale.filter(time__range=date_range).time_bucket('time', '1 hour')\n\n      # expected output\n\n      <TimescaleQuerySet [{'bucket': datetime.datetime(2020, 12, 22, 11, 0, tzinfo=<UTC>)}, ... ]>\n\nTime Bucket Gap Fill `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#gap-filling>`__\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n      from metrics.models import *\n      from django.db.models import Count, Avg\n      from django.utils import timezone\n      from datetime import timedelta\n\n      ranges = (timezone.now() - timedelta(days=2), timezone.now())\n\n      (Metric.timescale\n        .filter(time__range=ranges)\n        .time_bucket_gapfill('time', '1 day', ranges[0], ranges[1], datapoints=240)\n        .annotate(Avg('temperature')))\n\n      # expected output\n\n      <TimescaleQuerySet [{'bucket': datetime.datetime(2020, 12, 21, 21, 24, tzinfo=<UTC>), 'temperature__avg': None}, ...]>\n\nHistogram `More Info <https://docs.timescale.com/latest/using-timescaledb/reading-data#histogram>`__\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n      from metrics.models import *\n      from django.db.models import Count\n      from django.utils import timezone\n      from datetime import timedelta\n\n      ranges = (timezone.now() - timedelta(days=3), timezone.now())\n\n      (Metric.timescale\n        .filter(time__range=ranges)\n        .values('device')\n        .histogram(field='temperature', min_value=50.0, max_value=55.0, num_of_buckets=10)\n        .annotate(Count('device')))\n        \n      # expected output\n\n      <TimescaleQuerySet [{'histogram': [0, 0, 0, 87, 93, 125, 99, 59, 0, 0, 0, 0], 'device__count': 463}]>\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0 License",
    "summary": "A Django database backend for integration with TimescaleDB",
    "version": "0.2.13",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "859f88107d46771b0236a80db0ab4324650b73973187141f214b24f46b7c4cf2",
                "md5": "65c842b4c59c7058169f44a16ecf1bec",
                "sha256": "3a2dcdf224af318c6c813c7fbf323fa73ae9bd12d33cdf7540e34344ae62f739"
            },
            "downloads": -1,
            "filename": "django-timescaledb-0.2.13.tar.gz",
            "has_sig": false,
            "md5_digest": "65c842b4c59c7058169f44a16ecf1bec",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 13264,
            "upload_time": "2023-02-07T13:15:57",
            "upload_time_iso_8601": "2023-02-07T13:15:57.529749Z",
            "url": "https://files.pythonhosted.org/packages/85/9f/88107d46771b0236a80db0ab4324650b73973187141f214b24f46b7c4cf2/django-timescaledb-0.2.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-07 13:15:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "schlunsen",
    "github_project": "django-timescaledb",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-timescaledb"
}
        
Elapsed time: 0.04861s