├── .github └── workflows │ ├── ci-tests.yml │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── README.rst ├── example ├── iot_example_app │ ├── .env │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── metrics │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── management │ │ ├── __init__.py │ │ └── commands │ │ │ ├── __init__.py │ │ │ └── load_temperature.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20201221_2052.py │ │ ├── 0003_auto_20201222_1121.py │ │ ├── 0004_metric_device.py │ │ ├── 0005_rename_sampletest_anothermetricfromtimescalemodel.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── requirements.txt ├── setup.cfg ├── setup.py └── timescale ├── .DS_Store ├── __init__.py ├── db ├── .DS_Store ├── __init__.py ├── backends │ ├── .DS_Store │ ├── __init__.py │ ├── postgis │ │ ├── __init__.py │ │ ├── base.py │ │ ├── base_impl.py │ │ └── schema.py │ └── postgresql │ │ ├── __init__.py │ │ ├── base.py │ │ ├── base_impl.py │ │ └── schema.py ├── models │ ├── __init__.py │ ├── aggregates.py │ ├── expressions.py │ ├── fields.py │ ├── managers.py │ ├── models.py │ └── querysets.py └── operations.py └── tests ├── __init__.py ├── conftest.py ├── factories.py └── test_models.py /.github/workflows/ci-tests.yml: -------------------------------------------------------------------------------- 1 | name: Django timescaledb - Test basic project setup 2 | on: 3 | push: 4 | branches: [main] 5 | 6 | jobs: 7 | setup-example-project: 8 | runs-on: ubuntu-latest 9 | env: 10 | DB_NAME: test 11 | DB_USER: postgres 12 | DB_PORT: 5433 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python 3.7 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: 3.7 20 | 21 | - name: Checkout code 22 | uses: actions/checkout@v2 23 | 24 | - name: Install dependencies 25 | run: |- 26 | cd example 27 | pip install -r requirements.txt 28 | 29 | # Start timescaledb 30 | docker run -d --name timescaledb -p 5433:5432 -e POSTGRES_PASSWORD=password -e POSTGRES_DB=test timescale/timescaledb:2.5.1-pg14 31 | 32 | # Wait for db to be ready 33 | sleep 4 34 | 35 | # Migrate 36 | PYTHONPATH=../ python3 manage.py migrate 37 | 38 | - name: Run tests 39 | run: |- 40 | cd example 41 | PYTHONPATH=../ python3 manage.py test 42 | 43 | - name: Test alter field 44 | run: |- 45 | cd example 46 | sed -i -e 's/1 day/2 days/g' metrics/models.py 47 | PYTHONPATH=../ python3 manage.py makemigrations 48 | PYTHONPATH=../ python3 manage.py migrate 49 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Set up Python 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: "3.x" 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | pip install setuptools wheel twine 24 | - name: Build and publish 25 | env: 26 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 27 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 28 | run: | 29 | python setup.py sdist bdist_wheel 30 | twine upload dist/* -u "$TWINE_USERNAME" -p "$TWINE_PASSWORD" 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | dist/ 3 | build/ 4 | django_timescaledb.egg-info/ 5 | .venv 6 | *ipynb 7 | example/timescale 8 | .DS_STORE 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include timescale/ * 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django timescaledb 2 | 3 | [![PyPI version fury.io](https://badge.fury.io/py/django-timescaledb.svg)](https://pypi.python.org/pypi/django-timescaledb/) 4 | 5 | ![Workflow](https://github.com/schlunsen/django-timescaledb/actions/workflows/ci-tests.yml/badge.svg) 6 | 7 | A database backend and tooling for Timescaledb. 8 | 9 | Based on [gist](https://gist.github.com/dedsm/fc74f04eb70d78459ff0847ef16f2e7a) from WeRiot. 10 | 11 | ## Quick start 12 | 13 | 1. Install via pip 14 | 15 | ```bash 16 | pip install django-timescaledb 17 | ``` 18 | 19 | 2. Use as DATABASE engine in settings.py: 20 | 21 | Standard PostgreSQL 22 | 23 | ```python 24 | DATABASES = { 25 | 'default': { 26 | 'ENGINE': 'timescale.db.backends.postgresql', 27 | ... 28 | }, 29 | } 30 | ``` 31 | 32 | PostGIS 33 | 34 | ```python 35 | DATABASES = { 36 | 'default': { 37 | 'ENGINE': 'timescale.db.backends.postgis', 38 | ... 39 | }, 40 | } 41 | ``` 42 | 43 | If you already make use of a custom PostgreSQL db backend you can set the path in settings.py. 44 | 45 | ```python 46 | TIMESCALE_DB_BACKEND_BASE = "django.contrib.gis.db.backends.postgis" 47 | ``` 48 | 49 | 3. Inherit from the TimescaleModel. A [hypertable](https://docs.timescale.com/use-timescale/latest/hypertables/about-hypertables/) will automatically be created. 50 | 51 | ```python 52 | 53 | class TimescaleModel(models.Model): 54 | """ 55 | A helper class for using Timescale within Django, has the TimescaleManager and 56 | TimescaleDateTimeField already present. This is an abstract class it should 57 | be inheritted by another class for use. 58 | """ 59 | time = TimescaleDateTimeField(interval="1 day") 60 | 61 | objects = TimescaleManager() 62 | 63 | class Meta: 64 | abstract = True 65 | 66 | ``` 67 | 68 | Implementation would look like this 69 | 70 | ```python 71 | from timescale.db.models.models import TimescaleModel 72 | 73 | class Metric(TimescaleModel): 74 | temperature = models.FloatField() 75 | 76 | 77 | ``` 78 | 79 | 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. 80 | 81 | ```python 82 | from timescale.db.models.fields import TimescaleDateTimeField 83 | from timescale.db.models.managers import TimescaleManager 84 | 85 | class Metric(models.Model): 86 | time = TimescaleDateTimeField(interval="1 day") 87 | 88 | objects = models.Manager() 89 | timescale = TimescaleManager() 90 | ``` 91 | 92 | The name of the field is important as Timescale specific feratures require this as a property of their functions. 93 | 94 | ### Reading Data 95 | 96 | "TimescaleDB hypertables are designed to behave in the same manner as PostgreSQL database tables for reading data, using standard SQL commands." 97 | 98 | 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. 99 | 100 | #### Time Bucket [More Info](https://docs.timescale.com/use-timescale/latest/time-buckets/about-time-buckets/) 101 | 102 | ```python 103 | Metric.timescale.filter(time__range=date_range).time_bucket('time', '1 hour') 104 | 105 | # expected output 106 | 107 | )}, ... ]> 108 | ``` 109 | 110 | #### Time Bucket Gap Fill [More Info](https://docs.timescale.com/use-timescale/latest/hyperfunctions/gapfilling-interpolation/time-bucket-gapfill/) 111 | 112 | ```python 113 | from metrics.models import * 114 | from django.db.models import Count, Avg 115 | from django.utils import timezone 116 | from datetime import timedelta 117 | 118 | ranges = (timezone.now() - timedelta(days=2), timezone.now()) 119 | 120 | (Metric.timescale 121 | .filter(time__range=ranges) 122 | .time_bucket_gapfill('time', '1 day', ranges[0], ranges[1], datapoints=240) 123 | .annotate(Avg('temperature'))) 124 | 125 | # expected output 126 | 127 | ), 'temperature__avg': None}, ...]> 128 | ``` 129 | 130 | #### Histogram [More Info](https://docs.timescale.com/api/latest/hyperfunctions/histogram/) 131 | 132 | ```python 133 | from metrics.models import * 134 | from django.db.models import Count 135 | from django.utils import timezone 136 | from datetime import timedelta 137 | 138 | ranges = (timezone.now() - timedelta(days=3), timezone.now()) 139 | 140 | (Metric.timescale 141 | .filter(time__range=ranges) 142 | .values('device') 143 | .histogram(field='temperature', min_value=50.0, max_value=55.0, num_of_buckets=10) 144 | .annotate(Count('device'))) 145 | 146 | # expected output 147 | 148 | 149 | ``` 150 | 151 | ## Contributors 152 | - [Rasmus Schlünsen](https://github.com/schlunsen) 153 | - [Ben Cleary](https://github.com/bencleary) 154 | - [Jonathan Sundqvist](https://github.com/jonathan-s) 155 | - [Harsh Bhikadia](https://github.com/daadu) 156 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Django timescaledb 2 | ================== 3 | 4 | A database backend and tooling for Timescaledb. 5 | 6 | Based on 7 | `gist `__ 8 | from WeRiot. 9 | 10 | Quick start 11 | ----------- 12 | 13 | 1. Install via pip 14 | 15 | .. code:: bash 16 | 17 | pip install django-timescaledb 18 | 19 | 2. Use as DATABASE engine in settings.py: 20 | 21 | Standard PostgreSQL 22 | 23 | .. code:: python 24 | 25 | DATABASES = { 26 | 'default': { 27 | 'ENGINE': 'timescale.db.backends.postgresql', 28 | ... 29 | }, 30 | } 31 | 32 | PostGIS 33 | 34 | .. code:: python 35 | 36 | DATABASES = { 37 | 'default': { 38 | 'ENGINE': 'timescale.db.backends.postgis', 39 | ... 40 | }, 41 | } 42 | 43 | If you already make use of a custom PostgreSQL db backend you can set 44 | the path in settings.py. 45 | 46 | .. code:: python 47 | 48 | TIMESCALE_DB_BACKEND_BASE = "django.contrib.gis.db.backends.postgis" 49 | 50 | 3. Inherit from the TimescaleModel. A 51 | `hypertable `__ 52 | will automatically be created. 53 | 54 | .. code:: python 55 | 56 | 57 | class TimescaleModel(models.Model): 58 | """ 59 | A helper class for using Timescale within Django, has the TimescaleManager and 60 | TimescaleDateTimeField already present. This is an abstract class it should 61 | be inheritted by another class for use. 62 | """ 63 | time = TimescaleDateTimeField(interval="1 day") 64 | 65 | objects = TimescaleManager() 66 | 67 | class Meta: 68 | abstract = True 69 | 70 | Implementation would look like this 71 | 72 | .. code:: python 73 | 74 | from timescale.db.models.models import TimescaleModel 75 | 76 | class Metric(TimescaleModel): 77 | temperature = models.FloatField() 78 | 79 | 80 | If you already have a table, you can either add `time` 81 | field of type `TimescaleDateTimeField` to your model or 82 | rename (if not already named `time`) and change type of 83 | existing `DateTimeField` (rename first then run 84 | `makemigrations` and then change the type, so that 85 | `makemigrations` considers it as change in same field 86 | instead of removing and adding new field). This also 87 | triggers the creation of a hypertable. 88 | 89 | .. code:: python 90 | 91 | from timescale.db.models.fields import TimescaleDateTimeField 92 | from timescale.db.models.managers import TimescaleManager 93 | 94 | class Metric(models.Model): 95 | time = TimescaleDateTimeField(interval="1 day") 96 | 97 | objects = models.Manager() 98 | timescale = TimescaleManager() 99 | 100 | The name of the field is important as Timescale specific feratures 101 | require this as a property of their functions. ### Reading Data 102 | 103 | "TimescaleDB hypertables are designed to behave in the same manner as 104 | PostgreSQL database tables for reading data, using standard SQL 105 | commands." 106 | 107 | As such the use of the Django's ORM is perfectally suited to this type 108 | of data. By leveraging a custom model manager and queryset we can extend 109 | the queryset methods to include Timescale functions. 110 | 111 | Time Bucket `More Info `__ 112 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 113 | 114 | .. code:: python 115 | 116 | Metric.timescale.filter(time__range=date_range).time_bucket('time', '1 hour') 117 | 118 | # expected output 119 | 120 | )}, ... ]> 121 | 122 | Time Bucket Gap Fill `More Info `__ 123 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 124 | 125 | .. code:: python 126 | 127 | from metrics.models import * 128 | from django.db.models import Count, Avg 129 | from django.utils import timezone 130 | from datetime import timedelta 131 | 132 | ranges = (timezone.now() - timedelta(days=2), timezone.now()) 133 | 134 | (Metric.timescale 135 | .filter(time__range=ranges) 136 | .time_bucket_gapfill('time', '1 day', ranges[0], ranges[1], datapoints=240) 137 | .annotate(Avg('temperature'))) 138 | 139 | # expected output 140 | 141 | ), 'temperature__avg': None}, ...]> 142 | 143 | Histogram `More Info `__ 144 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 145 | 146 | .. code:: python 147 | 148 | from metrics.models import * 149 | from django.db.models import Count 150 | from django.utils import timezone 151 | from datetime import timedelta 152 | 153 | ranges = (timezone.now() - timedelta(days=3), timezone.now()) 154 | 155 | (Metric.timescale 156 | .filter(time__range=ranges) 157 | .values('device') 158 | .histogram(field='temperature', min_value=50.0, max_value=55.0, num_of_buckets=10) 159 | .annotate(Count('device'))) 160 | 161 | # expected output 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /example/iot_example_app/.env: -------------------------------------------------------------------------------- 1 | DB_DATABASE=test 2 | DB_USERNAME=postgres 3 | DB_PASSWORD=password 4 | DB_HOST=127.0.0.1 5 | DB_PORT=5433 6 | -------------------------------------------------------------------------------- /example/iot_example_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/example/iot_example_app/__init__.py -------------------------------------------------------------------------------- /example/iot_example_app/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for iot_example_app project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iot_example_app.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /example/iot_example_app/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for iot_example_app project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.1.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.1/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | from dotenv import load_dotenv 15 | import os 16 | 17 | load_dotenv() 18 | 19 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 20 | BASE_DIR = Path(__file__).resolve().parent.parent 21 | 22 | 23 | # Quick-start development settings - unsuitable for production 24 | # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ 25 | 26 | # SECURITY WARNING: keep the secret key used in production secret! 27 | SECRET_KEY = 'm#r0kagf+fk2r8e$8=2*g3v2(%e3*sb2a)l*_s+g0bg$zgpkr)' 28 | 29 | # SECURITY WARNING: don't run with debug turned on in production! 30 | DEBUG = True 31 | 32 | ALLOWED_HOSTS = [] 33 | 34 | 35 | # Application definition 36 | 37 | INSTALLED_APPS = [ 38 | 'django.contrib.admin', 39 | 'django.contrib.auth', 40 | 'django.contrib.contenttypes', 41 | 'django.contrib.sessions', 42 | 'django.contrib.messages', 43 | 'django.contrib.staticfiles', 44 | 'timescale', 45 | 'django_extensions', 46 | "metrics", 47 | ] 48 | 49 | MIDDLEWARE = [ 50 | 'django.middleware.security.SecurityMiddleware', 51 | 'django.contrib.sessions.middleware.SessionMiddleware', 52 | 'django.middleware.common.CommonMiddleware', 53 | 'django.middleware.csrf.CsrfViewMiddleware', 54 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 55 | 'django.contrib.messages.middleware.MessageMiddleware', 56 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 57 | ] 58 | 59 | ROOT_URLCONF = 'iot_example_app.urls' 60 | 61 | TEMPLATES = [ 62 | { 63 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 64 | 'DIRS': [], 65 | 'APP_DIRS': True, 66 | 'OPTIONS': { 67 | 'context_processors': [ 68 | 'django.template.context_processors.debug', 69 | 'django.template.context_processors.request', 70 | 'django.contrib.auth.context_processors.auth', 71 | 'django.contrib.messages.context_processors.messages', 72 | ], 73 | }, 74 | }, 75 | ] 76 | 77 | WSGI_APPLICATION = 'iot_example_app.wsgi.application' 78 | 79 | 80 | # Database 81 | # https://docs.djangoproject.com/en/3.1/ref/settings/#databases 82 | 83 | DATABASES = { 84 | 'default': { 85 | 'ENGINE': 'timescale.db.backends.postgresql', 86 | 'NAME': os.getenv('DB_DATABASE'), 87 | 'USER': os.getenv('DB_USERNAME'), 88 | 'PASSWORD': os.getenv('DB_PASSWORD'), 89 | 'HOST': os.getenv('DB_HOST'), 90 | 'PORT': os.getenv('DB_PORT'), 91 | } 92 | } 93 | 94 | 95 | # Password validation 96 | # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators 97 | 98 | AUTH_PASSWORD_VALIDATORS = [ 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 107 | }, 108 | { 109 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 110 | }, 111 | ] 112 | 113 | 114 | # Internationalization 115 | # https://docs.djangoproject.com/en/3.1/topics/i18n/ 116 | 117 | LANGUAGE_CODE = 'en-us' 118 | 119 | TIME_ZONE = 'UTC' 120 | 121 | USE_I18N = True 122 | 123 | USE_L10N = True 124 | 125 | USE_TZ = True 126 | 127 | 128 | # Static files (CSS, JavaScript, Images) 129 | # https://docs.djangoproject.com/en/3.1/howto/static-files/ 130 | 131 | STATIC_URL = '/static/' 132 | -------------------------------------------------------------------------------- /example/iot_example_app/urls.py: -------------------------------------------------------------------------------- 1 | """iot_example_app URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /example/iot_example_app/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for iot_example_app project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iot_example_app.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iot_example_app.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /example/metrics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/example/metrics/__init__.py -------------------------------------------------------------------------------- /example/metrics/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /example/metrics/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MetricsConfig(AppConfig): 5 | name = 'metrics' 6 | -------------------------------------------------------------------------------- /example/metrics/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/example/metrics/management/__init__.py -------------------------------------------------------------------------------- /example/metrics/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/example/metrics/management/commands/__init__.py -------------------------------------------------------------------------------- /example/metrics/management/commands/load_temperature.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand, CommandError 2 | from metrics.models import Metric 3 | from django.utils import timezone 4 | from random import uniform, choice 5 | from datetime import timedelta 6 | 7 | class Command(BaseCommand): 8 | help = 'Uses PSUTILS to read any temperature sensor and adds a record' 9 | DEVICES = [1234, 1245, 1236] 10 | 11 | def handle(self, *args, **options): 12 | for i in range(1000): 13 | timestamp = timezone.now() - timedelta(minutes=i * 5) 14 | Metric.objects.create(time=timestamp, temperature=uniform(51.1, 53.3), device=choice(self.DEVICES)) 15 | -------------------------------------------------------------------------------- /example/metrics/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.1.4 on 2020-12-21 15:32 2 | 3 | from django.db import migrations, models 4 | import timescale.db.models.fields 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Metric', 17 | fields=[ 18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('time', timescale.db.models.fields.TimescaleDateTimeField(interval='1 day')), 20 | ('temperature', models.FloatField(default=0.0)), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /example/metrics/migrations/0002_auto_20201221_2052.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.1.4 on 2020-12-21 20:52 2 | 3 | from django.db import migrations 4 | import django.db.models.manager 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('metrics', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterModelManagers( 15 | name='metric', 16 | managers=[ 17 | ('timescale', django.db.models.manager.Manager()), 18 | ], 19 | ), 20 | ] 21 | -------------------------------------------------------------------------------- /example/metrics/migrations/0003_auto_20201222_1121.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.1.4 on 2020-12-22 11:21 2 | 3 | from django.db import migrations, models 4 | import timescale.db.models.fields 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('metrics', '0002_auto_20201221_2052'), 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='SampleTest', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('time', timescale.db.models.fields.TimescaleDateTimeField(interval='1 day')), 19 | ('value', models.FloatField(default=0.0)), 20 | ], 21 | options={ 22 | 'abstract': False, 23 | }, 24 | ), 25 | migrations.AlterModelManagers( 26 | name='metric', 27 | managers=[ 28 | ], 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /example/metrics/migrations/0004_metric_device.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.1.4 on 2020-12-22 11:33 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('metrics', '0003_auto_20201222_1121'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name='metric', 15 | name='device', 16 | field=models.IntegerField(default=0), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /example/metrics/migrations/0005_rename_sampletest_anothermetricfromtimescalemodel.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2 on 2021-04-20 19:57 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('metrics', '0004_metric_device'), 10 | ] 11 | 12 | operations = [ 13 | migrations.RenameModel( 14 | old_name='SampleTest', 15 | new_name='AnotherMetricFromTimeScaleModel', 16 | ), 17 | ] 18 | -------------------------------------------------------------------------------- /example/metrics/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/example/metrics/migrations/__init__.py -------------------------------------------------------------------------------- /example/metrics/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from timescale.db.models.fields import TimescaleDateTimeField 3 | from typing import Dict 4 | 5 | from timescale.db.models.models import TimescaleModel 6 | from timescale.db.models.managers import TimescaleManager 7 | 8 | 9 | 10 | 11 | # Create your models here. 12 | class Metric(models.Model): 13 | time = TimescaleDateTimeField(interval="1 day") 14 | temperature = models.FloatField(default=0.0) 15 | device = models.IntegerField(default=0) 16 | 17 | objects = models.Manager() 18 | timescale = TimescaleManager() 19 | 20 | 21 | class AnotherMetricFromTimeScaleModel(TimescaleModel): 22 | value = models.FloatField(default=0.0) 23 | -------------------------------------------------------------------------------- /example/metrics/tests.py: -------------------------------------------------------------------------------- 1 | from timescale.db.models.fields import TimescaleDateTimeField 2 | from timescale.db.models.expressions import TimeBucketNG 3 | from metrics.models import Metric 4 | from django.utils import timezone 5 | from dateutil.relativedelta import relativedelta 6 | from django.test import TestCase 7 | from django.db.models import Avg 8 | from timescale.db.models.aggregates import First 9 | 10 | 11 | class TimescaleDBTests(TestCase): 12 | def setUp(self): 13 | super().setUp() 14 | 15 | def test_time_bucket_ng(self): 16 | timestamp = timezone.now().replace(day=1) 17 | 18 | # datapoints for current month 19 | Metric.objects.create(time=timestamp - relativedelta(days=15), temperature=8) 20 | Metric.objects.create(time=timestamp - relativedelta(days=10), temperature=10) 21 | 22 | # datapoints for last month 23 | Metric.objects.create(time=timestamp - relativedelta(months=1, days=15), temperature=14) 24 | Metric.objects.create(time=timestamp - relativedelta(months=1, days=10), temperature=12) 25 | 26 | # get all metrics, monthly aggregated 27 | metrics = Metric.timescale.time_bucket_ng('time', '1 month').annotate(Avg('temperature')) 28 | 29 | # verify 30 | self.assertEqual(metrics[0]["temperature__avg"], 9.0) 31 | self.assertEqual(metrics[1]["temperature__avg"], 13.0) 32 | 33 | # get first entry of the monthly aggregated datapoints 34 | metrics = (Metric.timescale 35 | .values(interval_end=TimeBucketNG('time', f'1 month', output_field=TimescaleDateTimeField(interval='1 month'))) 36 | .annotate(temperature__first=First('temperature', 'time'))) 37 | 38 | # verify 39 | # XXX: Remove 40 | self.assertEqual(metrics[0]["temperature__first"], 14.0) 41 | self.assertEqual(metrics[1]["temperature__first"], 8.0) 42 | 43 | -------------------------------------------------------------------------------- /example/metrics/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /example/requirements.txt: -------------------------------------------------------------------------------- 1 | Django 2 | psycopg2 3 | django-extensions 4 | python-dotenv 5 | dateutils 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = django-timescaledb 3 | version = 0.2.13 4 | description = A Django database backend for integration with TimescaleDB 5 | long_description = file: README.rst 6 | url = https://github.com/schlunsen/django-timescaledb 7 | author = Rasmus Schlünsen 8 | author_email = raller84@gmail.com 9 | license = Apache-2.0 License 10 | classifiers = 11 | Environment :: Web Environment 12 | Framework :: Django 13 | Framework :: Django :: 3.0 14 | Intended Audience :: Developers 15 | License :: OSI Approved :: BSD License 16 | Operating System :: OS Independent 17 | Programming Language :: Python 18 | Programming Language :: Python :: 3 19 | Programming Language :: Python :: 3 :: Only 20 | Programming Language :: Python :: 3.6 21 | Programming Language :: Python :: 3.7 22 | Programming Language :: Python :: 3.8 23 | Topic :: Internet :: WWW/HTTP 24 | Topic :: Internet :: WWW/HTTP :: Dynamic Content 25 | 26 | [options] 27 | include_package_data = true 28 | packages = find: 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /timescale/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/.DS_Store -------------------------------------------------------------------------------- /timescale/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/__init__.py -------------------------------------------------------------------------------- /timescale/db/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/.DS_Store -------------------------------------------------------------------------------- /timescale/db/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/__init__.py -------------------------------------------------------------------------------- /timescale/db/backends/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/backends/.DS_Store -------------------------------------------------------------------------------- /timescale/db/backends/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/backends/__init__.py -------------------------------------------------------------------------------- /timescale/db/backends/postgis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/backends/postgis/__init__.py -------------------------------------------------------------------------------- /timescale/db/backends/postgis/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.db import ProgrammingError 4 | from django.core.exceptions import ImproperlyConfigured 5 | 6 | from timescale.db.backends.postgis import base_impl 7 | from timescale.db.backends.postgis.schema import TimescaleSchemaEditor 8 | 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | class DatabaseWrapper(base_impl.backend()): 14 | SchemaEditorClass = TimescaleSchemaEditor 15 | 16 | def prepare_database(self): 17 | """Prepare the configured database. 18 | This is where we enable the `timescaledb` extension 19 | if it isn't enabled yet.""" 20 | 21 | super().prepare_database() 22 | with self.cursor() as cursor: 23 | try: 24 | cursor.execute('CREATE EXTENSION IF NOT EXISTS timescaledb') 25 | except ProgrammingError: # permission denied 26 | logger.warning( 27 | 'Failed to create "timescaledb" extension. ' 28 | 'Usage of timescale capabilities might fail' 29 | 'If timescale is needed, make sure you are connected ' 30 | 'to the database as a superuser ' 31 | 'or add the extension manually.', 32 | exc_info=True 33 | ) 34 | -------------------------------------------------------------------------------- /timescale/db/backends/postgis/base_impl.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import logging 3 | 4 | from django.db.backends.postgresql.base import ( # isort:skip 5 | DatabaseWrapper as Psycopg2DatabaseWrapper, 6 | ) 7 | 8 | from django.conf import settings 9 | from django.core.exceptions import ImproperlyConfigured 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def backend(): 15 | """Gets the base class for the custom database back-end. 16 | This should be the Django PostgreSQL back-end. However, 17 | some people are already using a custom back-end from 18 | another package. We are nice people and expose an option 19 | that allows them to configure the back-end we base upon. 20 | As long as the specified base eventually also has 21 | the PostgreSQL back-end as a base, then everything should 22 | work as intended. 23 | """ 24 | base_class_name = getattr( 25 | settings, 26 | "TIMESCALE_DB_BACKEND_BASE", 27 | "django.contrib.gis.db.backends.postgis", 28 | ) 29 | 30 | base_class_module = importlib.import_module(base_class_name + ".base") 31 | base_class = getattr(base_class_module, "DatabaseWrapper", None) 32 | 33 | if not base_class: 34 | raise ImproperlyConfigured( 35 | ( 36 | "'%s' is not a valid database back-end." 37 | " The module does not define a DatabaseWrapper class." 38 | " Check the value of TIMESCALE_EXTRA_DB_BACKEND_BASE." 39 | ) 40 | % base_class_name 41 | ) 42 | 43 | if isinstance(base_class, Psycopg2DatabaseWrapper): 44 | raise ImproperlyConfigured( 45 | ( 46 | "'%s' is not a valid database back-end." 47 | " It does inherit from the PostgreSQL back-end." 48 | " Check the value of TIMESCALE_EXTRA_DB_BACKEND_BASE." 49 | ) 50 | % base_class_name 51 | ) 52 | 53 | return base_class 54 | 55 | 56 | def schema_editor(): 57 | """Gets the base class for the schema editor. 58 | We have to use the configured base back-end's schema editor for 59 | this. 60 | """ 61 | 62 | return backend().SchemaEditorClass 63 | 64 | 65 | def introspection(): 66 | """Gets the base class for the introspection class. 67 | We have to use the configured base back-end's introspection class 68 | for this. 69 | """ 70 | 71 | return backend().introspection_class 72 | 73 | 74 | def operations(): 75 | """Gets the base class for the operations class. 76 | We have to use the configured base back-end's operations class for 77 | this. 78 | """ 79 | 80 | return backend().ops_class 81 | -------------------------------------------------------------------------------- /timescale/db/backends/postgis/schema.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.contrib.gis.db.backends.postgis.schema import PostGISSchemaEditor 3 | 4 | from timescale.db.models.fields import TimescaleDateTimeField 5 | 6 | 7 | class TimescaleSchemaEditor(PostGISSchemaEditor): 8 | sql_is_hypertable = '''SELECT * FROM timescaledb_information.hypertables 9 | WHERE hypertable_name = {table}{extra_condition}''' 10 | 11 | sql_assert_is_hypertable = ( 12 | 'DO $do$ BEGIN ' 13 | 'IF EXISTS ( ' 14 | + sql_is_hypertable + 15 | ') ' 16 | 'THEN NULL; ' 17 | 'ELSE RAISE EXCEPTION {error_message}; ' 18 | 'END IF;' 19 | 'END; $do$' 20 | ) 21 | sql_assert_is_not_hypertable = ( 22 | 'DO $do$ BEGIN ' 23 | 'IF EXISTS ( ' 24 | + sql_is_hypertable + 25 | ') ' 26 | 'THEN RAISE EXCEPTION {error_message}; ' 27 | 'ELSE NULL; ' 28 | 'END IF;' 29 | 'END; $do$' 30 | ) 31 | 32 | sql_drop_primary_key = 'ALTER TABLE {table} DROP CONSTRAINT {pkey}' 33 | 34 | sql_add_hypertable = ( 35 | "SELECT create_hypertable(" 36 | "{table}, {partition_column}, " 37 | "chunk_time_interval => interval {interval}, " 38 | "migrate_data => {migrate})" 39 | ) 40 | 41 | sql_set_chunk_time_interval = 'SELECT set_chunk_time_interval({table}, interval {interval})' 42 | 43 | sql_hypertable_is_in_schema = '''hypertable_schema = {schema_name}''' 44 | 45 | def _assert_is_hypertable(self, model): 46 | """ 47 | Assert if the table is a hyper table 48 | """ 49 | table = self.quote_value(model._meta.db_table) 50 | error_message = self.quote_value("assert failed - " + table + " should be a hyper table") 51 | 52 | extra_condition = self._get_extra_condition() 53 | 54 | sql = self.sql_assert_is_hypertable.format(table=table, error_message=error_message, 55 | extra_condition=extra_condition) 56 | 57 | self.execute(sql) 58 | 59 | def _assert_is_not_hypertable(self, model): 60 | """ 61 | Assert if the table is not a hyper table 62 | """ 63 | table = self.quote_value(model._meta.db_table) 64 | error_message = self.quote_value("assert failed - " + table + " should not be a hyper table") 65 | 66 | extra_condition = self._get_extra_condition() 67 | 68 | sql = self.sql_assert_is_not_hypertable.format(table=table, error_message=error_message, 69 | extra_condition=extra_condition) 70 | 71 | self.execute(sql) 72 | 73 | def _drop_primary_key(self, model): 74 | """ 75 | Hypertables can't partition if the primary key is not 76 | the partition column. 77 | So we drop the mandatory primary key django creates. 78 | """ 79 | db_table = model._meta.db_table 80 | table = self.quote_name(db_table) 81 | pkey_length = self.connection.ops.max_name_length() 82 | pkey = self.quote_name(f'{db_table[:pkey_length - 5]}_pkey') 83 | 84 | sql = self.sql_drop_primary_key.format(table=table, pkey=pkey) 85 | 86 | self.execute(sql) 87 | 88 | def _create_hypertable(self, model, field, should_migrate=False): 89 | """ 90 | Create the hypertable with the partition column being the field. 91 | """ 92 | # assert that the table is not already a hypertable 93 | self._assert_is_not_hypertable(model) 94 | 95 | # drop primary key of the table 96 | self._drop_primary_key(model) 97 | 98 | partition_column = self.quote_value(field.column) 99 | interval = self.quote_value(field.interval) 100 | table = self.quote_value(model._meta.db_table) 101 | migrate = "true" if should_migrate else "false" 102 | 103 | if should_migrate and getattr(settings, "TIMESCALE_MIGRATE_HYPERTABLE_WITH_FRESH_TABLE", False): 104 | # TODO migrate with fresh table [https://github.com/schlunsen/django-timescaledb/issues/16] 105 | raise NotImplementedError() 106 | else: 107 | sql = self.sql_add_hypertable.format( 108 | table=table, partition_column=partition_column, interval=interval, migrate=migrate 109 | ) 110 | self.execute(sql) 111 | 112 | def _set_chunk_time_interval(self, model, field): 113 | """ 114 | Change time interval for hypertable 115 | """ 116 | # assert if already a hypertable 117 | self._assert_is_hypertable(model) 118 | 119 | table = self.quote_value(model._meta.db_table) 120 | interval = self.quote_value(field.interval) 121 | 122 | sql = self.sql_set_chunk_time_interval.format(table=table, interval=interval) 123 | self.execute(sql) 124 | 125 | def create_model(self, model): 126 | super().create_model(model) 127 | 128 | # scan if any field is of instance `TimescaleDateTimeField` 129 | for field in model._meta.local_fields: 130 | if isinstance(field, TimescaleDateTimeField): 131 | # create hypertable, with the field as partition column 132 | self._create_hypertable(model, field) 133 | break 134 | 135 | def add_field(self, model, field): 136 | super().add_field(model, field) 137 | 138 | # check if this field is type `TimescaleDateTimeField` 139 | if isinstance(field, TimescaleDateTimeField): 140 | # migrate existing table to hypertable 141 | self._create_hypertable(model, field, True) 142 | 143 | def alter_field(self, model, old_field, new_field, strict=False): 144 | super().alter_field(model, old_field, new_field, strict) 145 | 146 | # check if old_field is not type `TimescaleDateTimeField` and new_field is 147 | if not isinstance(old_field, TimescaleDateTimeField) and isinstance(new_field, TimescaleDateTimeField): 148 | # migrate existing table to hypertable 149 | self._create_hypertable(model, new_field, True) 150 | # check if old_field and new_field is type `TimescaleDateTimeField` and `interval` is changed 151 | elif isinstance(old_field, TimescaleDateTimeField) and isinstance(new_field, TimescaleDateTimeField) \ 152 | and old_field.interval != new_field.interval: 153 | # change chunk-size 154 | self._set_chunk_time_interval(model, new_field) 155 | 156 | def _get_extra_condition(self): 157 | extra_condition = '' 158 | 159 | try: 160 | if self.connection.schema_name: 161 | schema_name = self.quote_value(self.connection.schema_name) 162 | extra_condition = ' AND ' + self.sql_hypertable_is_in_schema.format(schema_name=schema_name) 163 | except: 164 | pass 165 | 166 | return extra_condition 167 | -------------------------------------------------------------------------------- /timescale/db/backends/postgresql/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/backends/postgresql/__init__.py -------------------------------------------------------------------------------- /timescale/db/backends/postgresql/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.db import ProgrammingError 4 | from django.core.exceptions import ImproperlyConfigured 5 | 6 | from timescale.db.backends.postgresql import base_impl 7 | from timescale.db.backends.postgresql.schema import TimescaleSchemaEditor 8 | 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | class DatabaseWrapper(base_impl.backend()): 14 | SchemaEditorClass = TimescaleSchemaEditor 15 | 16 | def prepare_database(self): 17 | """Prepare the configured database. 18 | This is where we enable the `timescaledb` extension 19 | if it isn't enabled yet.""" 20 | 21 | super().prepare_database() 22 | with self.cursor() as cursor: 23 | try: 24 | cursor.execute('CREATE EXTENSION IF NOT EXISTS timescaledb') 25 | except ProgrammingError: # permission denied 26 | logger.warning( 27 | 'Failed to create "timescaledb" extension. ' 28 | 'Usage of timescale capabilities might fail' 29 | 'If timescale is needed, make sure you are connected ' 30 | 'to the database as a superuser ' 31 | 'or add the extension manually.', 32 | exc_info=True 33 | ) 34 | -------------------------------------------------------------------------------- /timescale/db/backends/postgresql/base_impl.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import logging 3 | 4 | from django.db.backends.postgresql.base import ( # isort:skip 5 | DatabaseWrapper as Psycopg2DatabaseWrapper, 6 | ) 7 | 8 | from django.conf import settings 9 | from django.core.exceptions import ImproperlyConfigured 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def backend(): 15 | """Gets the base class for the custom database back-end. 16 | This should be the Django PostgreSQL back-end. However, 17 | some people are already using a custom back-end from 18 | another package. We are nice people and expose an option 19 | that allows them to configure the back-end we base upon. 20 | As long as the specified base eventually also has 21 | the PostgreSQL back-end as a base, then everything should 22 | work as intended. 23 | """ 24 | base_class_name = getattr( 25 | settings, 26 | "TIMESCALE_DB_BACKEND_BASE", 27 | "django.db.backends.postgresql", 28 | ) 29 | 30 | base_class_module = importlib.import_module(base_class_name + ".base") 31 | base_class = getattr(base_class_module, "DatabaseWrapper", None) 32 | 33 | if not base_class: 34 | raise ImproperlyConfigured( 35 | ( 36 | "'%s' is not a valid database back-end." 37 | " The module does not define a DatabaseWrapper class." 38 | " Check the value of TIMESCALE_EXTRA_DB_BACKEND_BASE." 39 | ) 40 | % base_class_name 41 | ) 42 | 43 | if isinstance(base_class, Psycopg2DatabaseWrapper): 44 | raise ImproperlyConfigured( 45 | ( 46 | "'%s' is not a valid database back-end." 47 | " It does inherit from the PostgreSQL back-end." 48 | " Check the value of TIMESCALE_EXTRA_DB_BACKEND_BASE." 49 | ) 50 | % base_class_name 51 | ) 52 | 53 | return base_class 54 | 55 | 56 | def schema_editor(): 57 | """Gets the base class for the schema editor. 58 | We have to use the configured base back-end's schema editor for 59 | this. 60 | """ 61 | 62 | return backend().SchemaEditorClass 63 | 64 | 65 | def introspection(): 66 | """Gets the base class for the introspection class. 67 | We have to use the configured base back-end's introspection class 68 | for this. 69 | """ 70 | 71 | return backend().introspection_class 72 | 73 | 74 | def operations(): 75 | """Gets the base class for the operations class. 76 | We have to use the configured base back-end's operations class for 77 | this. 78 | """ 79 | 80 | return backend().ops_class 81 | -------------------------------------------------------------------------------- /timescale/db/backends/postgresql/schema.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.db.backends.postgresql.schema import DatabaseSchemaEditor 3 | 4 | from timescale.db.models.fields import TimescaleDateTimeField 5 | 6 | 7 | class TimescaleSchemaEditor(DatabaseSchemaEditor): 8 | sql_is_hypertable = '''SELECT * FROM timescaledb_information.hypertables 9 | WHERE hypertable_name = {table}{extra_condition}''' 10 | 11 | sql_assert_is_hypertable = ( 12 | 'DO $do$ BEGIN ' 13 | 'IF EXISTS ( ' 14 | + sql_is_hypertable + 15 | ') ' 16 | 'THEN NULL; ' 17 | 'ELSE RAISE EXCEPTION {error_message}; ' 18 | 'END IF;' 19 | 'END; $do$' 20 | ) 21 | sql_assert_is_not_hypertable = ( 22 | 'DO $do$ BEGIN ' 23 | 'IF EXISTS ( ' 24 | + sql_is_hypertable + 25 | ') ' 26 | 'THEN RAISE EXCEPTION {error_message}; ' 27 | 'ELSE NULL; ' 28 | 'END IF;' 29 | 'END; $do$' 30 | ) 31 | 32 | sql_drop_primary_key = 'ALTER TABLE {table} DROP CONSTRAINT {pkey}' 33 | 34 | sql_add_hypertable = ( 35 | "SELECT create_hypertable(" 36 | "{table}, {partition_column}, " 37 | "chunk_time_interval => interval {interval}, " 38 | "migrate_data => {migrate})" 39 | ) 40 | 41 | sql_set_chunk_time_interval = 'SELECT set_chunk_time_interval({table}, interval {interval})' 42 | 43 | sql_hypertable_is_in_schema = '''hypertable_schema = {schema_name}''' 44 | 45 | def _assert_is_hypertable(self, model): 46 | """ 47 | Assert if the table is a hyper table 48 | """ 49 | table = self.quote_value(model._meta.db_table) 50 | error_message = self.quote_value("assert failed - " + table + " should be a hyper table") 51 | 52 | extra_condition = self._get_extra_condition() 53 | 54 | sql = self.sql_assert_is_hypertable.format(table=table, error_message=error_message, 55 | extra_condition=extra_condition) 56 | 57 | self.execute(sql) 58 | 59 | def _assert_is_not_hypertable(self, model): 60 | """ 61 | Assert if the table is not a hyper table 62 | """ 63 | table = self.quote_value(model._meta.db_table) 64 | error_message = self.quote_value("assert failed - " + table + " should not be a hyper table") 65 | 66 | extra_condition = self._get_extra_condition() 67 | 68 | sql = self.sql_assert_is_not_hypertable.format(table=table, error_message=error_message, 69 | extra_condition=extra_condition) 70 | 71 | self.execute(sql) 72 | 73 | def _drop_primary_key(self, model): 74 | """ 75 | Hypertables can't partition if the primary key is not 76 | the partition column. 77 | So we drop the mandatory primary key django creates. 78 | """ 79 | db_table = model._meta.db_table 80 | table = self.quote_name(db_table) 81 | pkey_length = self.connection.ops.max_name_length() 82 | pkey = self.quote_name(f'{db_table[:pkey_length - 5]}_pkey') 83 | 84 | sql = self.sql_drop_primary_key.format(table=table, pkey=pkey) 85 | 86 | self.execute(sql) 87 | 88 | def _create_hypertable(self, model, field, should_migrate=False): 89 | """ 90 | Create the hypertable with the partition column being the field. 91 | """ 92 | # assert that the table is not already a hypertable 93 | self._assert_is_not_hypertable(model) 94 | 95 | # drop primary key of the table 96 | self._drop_primary_key(model) 97 | 98 | partition_column = self.quote_value(field.column) 99 | interval = self.quote_value(field.interval) 100 | table = self.quote_value(model._meta.db_table) 101 | migrate = "true" if should_migrate else "false" 102 | 103 | if should_migrate and getattr(settings, "TIMESCALE_MIGRATE_HYPERTABLE_WITH_FRESH_TABLE", False): 104 | # TODO migrate with fresh table [https://github.com/schlunsen/django-timescaledb/issues/16] 105 | raise NotImplementedError() 106 | else: 107 | sql = self.sql_add_hypertable.format( 108 | table=table, partition_column=partition_column, interval=interval, migrate=migrate 109 | ) 110 | self.execute(sql) 111 | 112 | def _set_chunk_time_interval(self, model, field): 113 | """ 114 | Change time interval for hypertable 115 | """ 116 | # assert if already a hypertable 117 | self._assert_is_hypertable(model) 118 | 119 | table = self.quote_value(model._meta.db_table) 120 | interval = self.quote_value(field.interval) 121 | 122 | sql = self.sql_set_chunk_time_interval.format(table=table, interval=interval) 123 | self.execute(sql) 124 | 125 | def create_model(self, model): 126 | super().create_model(model) 127 | 128 | # scan if any field is of instance `TimescaleDateTimeField` 129 | for field in model._meta.local_fields: 130 | if isinstance(field, TimescaleDateTimeField): 131 | # create hypertable, with the field as partition column 132 | self._create_hypertable(model, field) 133 | break 134 | 135 | def add_field(self, model, field): 136 | super().add_field(model, field) 137 | 138 | # check if this field is type `TimescaleDateTimeField` 139 | if isinstance(field, TimescaleDateTimeField): 140 | # migrate existing table to hypertable 141 | self._create_hypertable(model, field, True) 142 | 143 | def alter_field(self, model, old_field, new_field, strict=False): 144 | super().alter_field(model, old_field, new_field, strict) 145 | 146 | # check if old_field is not type `TimescaleDateTimeField` and new_field is 147 | if not isinstance(old_field, TimescaleDateTimeField) and isinstance(new_field, TimescaleDateTimeField): 148 | # migrate existing table to hypertable 149 | self._create_hypertable(model, new_field, True) 150 | # check if old_field and new_field is type `TimescaleDateTimeField` and `interval` is changed 151 | elif isinstance(old_field, TimescaleDateTimeField) and isinstance(new_field, TimescaleDateTimeField) \ 152 | and old_field.interval != new_field.interval: 153 | # change chunk-size 154 | self._set_chunk_time_interval(model, new_field) 155 | 156 | def _get_extra_condition(self): 157 | extra_condition = '' 158 | 159 | try: 160 | if self.connection.schema_name: 161 | schema_name = self.quote_value(self.connection.schema_name) 162 | extra_condition = ' AND ' + self.sql_hypertable_is_in_schema.format(schema_name=schema_name) 163 | except: 164 | pass 165 | 166 | return extra_condition 167 | -------------------------------------------------------------------------------- /timescale/db/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/db/models/__init__.py -------------------------------------------------------------------------------- /timescale/db/models/aggregates.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.postgres.fields import ArrayField 3 | from django.db.models.fields import FloatField 4 | 5 | 6 | class Histogram(models.Aggregate): 7 | """ 8 | Implementation of the histogram function from Timescale. 9 | 10 | Read more about it here - https://docs.timescale.com/latest/using-timescaledb/reading-data#histogram 11 | 12 | Response: 13 | 14 | 15 | 16 | """ 17 | function = 'histogram' 18 | name = 'histogram' 19 | output_field = ArrayField(models.FloatField()) 20 | 21 | def __init__(self, expression, min_value, max_value, bucket): 22 | super().__init__(expression, min_value, max_value, bucket) 23 | 24 | 25 | class LTTB(models.Func): 26 | function = 'lttb' 27 | name = 'lttb' 28 | output_field = models.DateTimeField() 29 | 30 | def __init__(self, time, value, count, field): 31 | self.fieldname = field 32 | super().__init__(time, value, count) 33 | 34 | def as_sql(self, compiler, connection, **extra_context): 35 | sql, params = super().as_sql(compiler, connection, **extra_context) 36 | return f'(unnest({sql})).{self.fieldname}', params 37 | 38 | 39 | class Last(models.Aggregate): 40 | function = 'last' 41 | name = 'last' 42 | output_field = FloatField() 43 | 44 | def __init__(self, expression, bucket): 45 | super().__init__(expression, bucket) 46 | 47 | 48 | class First(models.Aggregate): 49 | function = 'first' 50 | name = 'first' 51 | output_field = FloatField() 52 | 53 | def __init__(self, expression, bucket): 54 | super().__init__(expression, bucket) -------------------------------------------------------------------------------- /timescale/db/models/expressions.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.postgres.fields import ArrayField 3 | from django.db.models.functions.mixins import ( 4 | FixDurationInputMixin, 5 | NumericOutputFieldMixin, 6 | ) 7 | from django.utils import timezone 8 | from datetime import timedelta 9 | from timescale.db.models.fields import TimescaleDateTimeField 10 | 11 | 12 | class Interval(models.Func): 13 | """ 14 | A helper class to format the interval used by the time_bucket_gapfill function to generate correct timestamps. 15 | Accepts an interval e.g '1 day', '5 days', '1 hour' 16 | """ 17 | 18 | function = "INTERVAL" 19 | template = "%(function)s %(expressions)s" 20 | 21 | def __init__(self, interval, *args, **kwargs): 22 | if not isinstance(interval, models.Value): 23 | interval = models.Value(interval) 24 | super().__init__(interval, *args, **kwargs) 25 | 26 | 27 | class TimeBucket(models.Func): 28 | """ 29 | Implementation of the time_bucket function from Timescale. 30 | 31 | Read more about it here - https://docs.timescale.com/latest/using-timescaledb/reading-data#time-bucket 32 | 33 | Response: 34 | 35 | [ 36 | {'bucket': '2020-12-22T10:00:00+00:00', 'devices': 12}, 37 | {'bucket': '2020-12-22T09:00:00+00:00', 'devices': 12}, 38 | {'bucket': '2020-12-22T08:00:00+00:00', 'devices': 12}, 39 | {'bucket': '2020-12-22T07:00:00+00:00', 'devices': 12}, 40 | ] 41 | 42 | """ 43 | 44 | function = "time_bucket" 45 | name = "time_bucket" 46 | 47 | 48 | def __init__(self, expression, interval, offset=None, origin=None, *args, **kwargs): 49 | if not isinstance(interval, models.Value): 50 | interval = models.Value(interval) 51 | args = [interval, expression] 52 | if origin is not None: 53 | args.append(origin) 54 | elif offset is not None: 55 | if not isinstance(offset, models.Value): 56 | offset = models.Value(offset) 57 | args.append(offset) 58 | output_field = TimescaleDateTimeField(interval=interval) 59 | super().__init__(*args, output_field=output_field) 60 | 61 | 62 | class TimeBucketNG(models.Func): 63 | """ 64 | Implementation of the time_bucket_ng function from Timescale. 65 | 66 | Read more about it here - https://docs.timescale.com/api/latest/hyperfunctions/time_bucket_ng/#timescaledb-experimental-time-bucket-ng 67 | 68 | Response: 69 | 70 | [ 71 | {'bucket': '2020-12-01T00:00:00+00:00', 'devices': 12}, 72 | {'bucket': '2020-11-01T00:00:00+00:00', 'devices': 12}, 73 | {'bucket': '2020-10-01T00:00:00+00:00', 'devices': 12}, 74 | {'bucket': '2020-09-01T00:00:00+00:00', 'devices': 12}, 75 | ] 76 | 77 | """ 78 | 79 | function = "timescaledb_experimental.time_bucket_ng" 80 | name = "timescaledb_experimental.time_bucket_ng" 81 | 82 | def __init__(self, expression, interval, *args, **kwargs): 83 | if not isinstance(interval, models.Value): 84 | interval = models.Value(interval) 85 | output_field = TimescaleDateTimeField(interval=interval) 86 | super().__init__(interval, expression, output_field=output_field) 87 | 88 | 89 | class TimeBucketGapFill(models.Func): 90 | """ 91 | IMplementation of the time_bucket_gapfill function from Timescale 92 | 93 | Read more about it here - https://docs.timescale.com/latest/using-timescaledb/reading-data#gap-filling 94 | 95 | Response: 96 | 97 | [ 98 | ... 99 | {'bucket': '2020-12-22T11:36:00+00:00', 'temperature__avg': 52.7127405105567}, 100 | {'bucket': '2020-12-22T11:42:00+00:00', 'temperature__avg': None}, 101 | ... 102 | ] 103 | """ 104 | 105 | function = "time_bucket_gapfill" 106 | name = "time_bucket_gapfill" 107 | 108 | def __init__( 109 | self, expression, interval, start, end, datapoints=None, *args, **kwargs 110 | ): 111 | if not isinstance(interval, models.Value): 112 | interval = Interval(interval) 113 | if datapoints: 114 | interval = interval / datapoints 115 | output_field = TimescaleDateTimeField(interval=interval) 116 | super().__init__(interval, expression, start, end, output_field=output_field) 117 | -------------------------------------------------------------------------------- /timescale/db/models/fields.py: -------------------------------------------------------------------------------- 1 | from django.db.models import DateTimeField 2 | 3 | 4 | class TimescaleDateTimeField(DateTimeField): 5 | def __init__(self, *args, interval, **kwargs): 6 | self.interval = interval 7 | super().__init__(*args, **kwargs) 8 | 9 | def deconstruct(self): 10 | name, path, args, kwargs = super().deconstruct() 11 | kwargs['interval'] = self.interval 12 | 13 | return name, path, args, kwargs -------------------------------------------------------------------------------- /timescale/db/models/managers.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from timescale.db.models.querysets import * 3 | from typing import Optional 4 | 5 | 6 | class TimescaleManager(models.Manager): 7 | """ 8 | A custom model manager specifically designed around the Timescale 9 | functions and tooling that has been ported to Django's ORM. 10 | """ 11 | 12 | def get_queryset(self): 13 | return TimescaleQuerySet(self.model, using=self._db) 14 | 15 | def time_bucket(self, field, interval): 16 | return self.get_queryset().time_bucket(field, interval) 17 | 18 | def time_bucket_ng(self, field, interval): 19 | return self.get_queryset().time_bucket_ng(field, interval) 20 | 21 | def time_bucket_gapfill(self, field: str, interval: str, start: datetime, end: datetime, datapoints: Optional[int] = None): 22 | return self.get_queryset().time_bucket_gapfill(field, interval, start, end, datapoints) 23 | 24 | def histogram(self, field: str, min_value: float, max_value: float, num_of_buckets: int = 5): 25 | return self.get_queryset().histogram(field, min_value, max_value, num_of_buckets) 26 | 27 | def lttb(self, time: str, value: str, num_of_counts: int = 20): 28 | return self.get_queryset().lttb(time, value, num_of_counts) 29 | -------------------------------------------------------------------------------- /timescale/db/models/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from timescale.db.models.fields import TimescaleDateTimeField 3 | from timescale.db.models.managers import TimescaleManager 4 | 5 | 6 | class TimescaleModel(models.Model): 7 | """ 8 | A helper class for using Timescale within Django, has the TimescaleManager and 9 | TimescaleDateTimeField already present. This is an abstract class it should 10 | be inheritted by another class for use. 11 | """ 12 | time = TimescaleDateTimeField(interval="1 day") 13 | 14 | objects = models.Manager() 15 | timescale = TimescaleManager() 16 | 17 | 18 | class Meta: 19 | abstract = True -------------------------------------------------------------------------------- /timescale/db/models/querysets.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from timescale.db.models.expressions import TimeBucket, TimeBucketGapFill, TimeBucketNG 3 | from timescale.db.models.aggregates import Histogram, LTTB 4 | from typing import Dict, Optional 5 | from datetime import datetime 6 | 7 | 8 | class TimescaleQuerySet(models.QuerySet): 9 | 10 | def time_bucket(self, field: str, interval: str, annotations: Dict = None): 11 | """ 12 | Wraps the TimescaleDB time_bucket function into a queryset method. 13 | """ 14 | if annotations: 15 | return self.values(bucket=TimeBucket(field, interval)).order_by('-bucket').annotate(**annotations) 16 | return self.values(bucket=TimeBucket(field, interval)).order_by('-bucket') 17 | 18 | def time_bucket_ng(self, field: str, interval: str, annotations: Dict = None): 19 | """ 20 | Wraps the TimescaleDB time_bucket_ng function into a queryset method. 21 | """ 22 | if annotations: 23 | return self.values(bucket=TimeBucketNG(field, interval)).order_by('-bucket').annotate(**annotations) 24 | return self.values(bucket=TimeBucketNG(field, interval)).order_by('-bucket') 25 | 26 | def time_bucket_gapfill(self, field: str, interval: str, start: datetime, end: datetime, datapoints: Optional[int] = None): 27 | """ 28 | Wraps the TimescaleDB time_bucket_gapfill function into a queryset method. 29 | """ 30 | return self.values(bucket=TimeBucketGapFill(field, interval, start, end, datapoints)) 31 | 32 | def histogram(self, field: str, min_value: float, max_value: float, num_of_buckets: int = 5): 33 | """ 34 | Wraps the TimescaleDB histogram function into a queryset method. 35 | """ 36 | return self.values(histogram=Histogram(field, min_value, max_value, num_of_buckets)) 37 | 38 | def lttb(self, time: str, value: str, num_of_counts: int = 20): 39 | """ 40 | Wraps the TimescaleDB toolkit lttb function into a queryset method. 41 | """ 42 | return self.values( 43 | lttb_t=LTTB(time, value, num_of_counts, time), 44 | lttb_v=LTTB(time, value, num_of_counts, value) 45 | ) 46 | 47 | def to_list(self, normalise_datetimes: bool = False): 48 | if normalise_datetimes: 49 | normalised = [] 50 | for b in list(self): 51 | b["bucket"] = b["bucket"].isoformat() 52 | normalised.append(b) 53 | return normalised 54 | return list(self) 55 | -------------------------------------------------------------------------------- /timescale/db/operations.py: -------------------------------------------------------------------------------- 1 | from django.contrib.postgres.operations import CreateExtension 2 | 3 | 4 | class TimescaleExtension(CreateExtension): 5 | def __init__(self): 6 | self.name = "timescaledb" -------------------------------------------------------------------------------- /timescale/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/tests/__init__.py -------------------------------------------------------------------------------- /timescale/tests/conftest.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/tests/conftest.py -------------------------------------------------------------------------------- /timescale/tests/factories.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/tests/factories.py -------------------------------------------------------------------------------- /timescale/tests/test_models.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamessewell/django-timescaledb/b749b60e794f7a9ddf14b85ea3ccb6b71c3146a2/timescale/tests/test_models.py --------------------------------------------------------------------------------