TimescaleDB 中使用 Django 作为框架的多个时间序列

问题描述 投票:0回答:1

我正在尝试在 timescaledb 中设置多个时间序列。问题在于不同的记录具有相同的时间戳,例如

from django.db import models
from timescale.db.models.models import TimescaleModel
from .assets import Asset  

class TimeseriesData(TimescaleModel):
    time = models.DateTimeField(primary_key=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    close_price = models.DecimalField(max_digits=10, decimal_places=2)
    volume = models.BigIntegerField()

    class Meta:
        unique_together = (('time', 'asset'),)  # Create a composite unique constraint

    

我可能拥有相同时间的不同资产,而 timescaledb 需要时间作为主键,那么我该如何解决这个问题?为每个资产创建一个新的 timescalemodel 感觉不好,这是 timescaledb 应该如何使用的吗?

我尝试添加 id 列作为主键,但它失败了,因为 timescaledb 需要时间作为 pk,我不知道还可以尝试什么。

django postgresql time-series timescaledb
1个回答
0
投票

Timescale 不需要时间作为主键。

根据 django-timescaledb 文档

TimescaleModel
定义为:

  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

其中已包含

time
定义作为时间字段,并将定义 1 天的块大小。

将代码更改为:

from django.db import models
from timescale.db.models.models import TimescaleModel
from .assets import Asset  

class TimeseriesData(TimescaleModel):
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)
    close_price = models.DecimalField(max_digits=10, decimal_places=2)
    volume = models.BigIntegerField()
    
class Meta:
        unique_together = (('time', 'asset'),)  # Create a composite unique constraint

在大多数情况下,您希望

time
列成为索引的最后一列:

来自关于索引数据的Timescale文档

索引的一个好的经验法则是分层思考。首先选择您通常想要运行等式运算符的列,例如 location = Garage。然后通过选择要使用范围运算符的列来完成,例如时间 > 0930。

© www.soinside.com 2019 - 2024. All rights reserved.