XandrOSS
XandrOSS

Reputation: 1

How to deal with Django and TimescaleDB hypertables?

Firstly hypertable needs all PK contains partition column, in this case time, and in the other hand Django does not allow create multi column PK so you can't create a PK that could contains the time column.

Second: if I have rows with repeated time, it will break unique constraints in time column.

How can you use Django and TimescaleDB together and make use of hypertables?

I have tried to create a table with time as primary key and eventually I have got duplicate key error inserting data in the table

Upvotes: 0

Views: 379

Answers (1)

alejandrodnm
alejandrodnm

Reputation: 5640

There's a Django library for Timescale

https://github.com/jamessewell/django-timescaledb

It has a model manager with some basic functions, takes care of installing the extension and creating hypertables.

I haven't looked to deep into the code, but it works by removing the pk of the model tables.

You can install it with

pip install django-timescaledb

Add it to your settings.py:

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

Create your model like:

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()

Upvotes: 0

Related Questions