这里的标准方法是使用Django模型(转换为db中的表):
BuoyData
类将具有ForeignKey
模型的Buoy
。
还要查看GeoDjango,以存储和查询经纬度。您将要使用PointField
中的django.contrib.gis.db.models
。以下是一些示例模型:
from django.contrib.gis.db import models
class Buoy(models.Model):
"""
Represents a Buoy
"""
location = models.PointField()
name = models.CharField(max_length=200,null=True,blank=True)
class BuoyData(models.Model):
"""
Represents a single Buoy datapoint
"""
buoy = models.ForeignKey(Buoy,related_name='data')
date = models.DateTimeField()
# swell size in feet
swell_size_ft = models.DecimalField(decimal_places=2,max_digits=5)
然后您可以在经度或纬度附近或附近查询Buoy
,然后查询Buoy
的数据。
django_pandas软件包具有将Django Queryset读取到Pandas数据框中的非常有用的方法:
from django_pandas.io import read_frame
buoy = Buoy.objects.get(id=10)
data_queryset = buoy.data.all()
df = read_frame(data_queryset)
# or another example
import datetime
from django.utils import timezone
from django.contrib.gis.geos import Point
lat = 36.123
lng = -121.123
# notice how lng is x,lat is y
location = Point(lng,lat)
time_four_days_ago = timezone.now() - datetime.timedelta(days=4)
closest_buoy = Buoy.objects.distance(location).order_by('distance')[0]
data_queryset = buoy.data.filter(date__gte=time_four_days_ago)
# if there are a lot of fields on your BuoyData model,# and you only need a few,.values will be more performant
data_values = data_queryset.values('date','swell_size_ft')
df = read_frame(data_values)
为什么您的方法无效:
关系数据库(MySQL,Postgresql)通常将数据存储在固定大小的空间中。浮标可能有数百万个时间序列数据点,并且可能每隔几秒钟添加一次新数据。您不知道单个浮标的所有将来数据会有多大。
设置数据库时,您需要为特定模型的每个字段设置大小上限。例如,文本字段具有max_length属性。当然,某些类型的字段支持非常大的最大大小,但这会影响数据库的性能。
相反,您需要创建一个单独的表来存储所有数据Buoys
。该表中的每一行都是单独的时间序列数据。此数据库中的一个字段(列)将是数据所属的id
中的Buoy
。此字段由Django ForeignKey自动创建和填充。
,
截至 2021 年,现在有一个库可以将简单的时间序列向量作为自定义 Django 字段存储在数据库中:django-simple-timeseries
。
class Buoy(models.Model):
location = models.PointField()
name = models.CharField(max_length=200,blank=True)
swell_size_ft = TimeseriesField(max_points=100,resolution_seconds=3600)
这对于小时间序列来说是一个方便的选项,并且可以安全地截断数据(在 max_points
之后)。
(免责声明:我根据自己的需要编写了这个库,这与提问者的类似。)
本文链接:https://www.f2er.com/3070660.html