我正在尝试为时间序列数据构建数据存储,为此我创建了嵌套对象 Coin 和 Data,其中 Coin 是父对象并包含每个数据条目是单个对象的数据条目。此刻,我的代码在 CoinSerializer 中构建创建函数时创建了嵌套对象 Coin[Data],但我无法使用正确的方法在现有 Coin 对象中添加/创建子对象
在我的 python 虚拟环境中,我一直在使用 django 2.1.4 drf 3.9 和 python 3.6 .. 也作为我项目的后端数据库引擎,我得到了 mongodb 并使用 djongo 1.2 来维护它
任何针对我的问题提出的想法或方法将不胜感激,因为这是我的第一篇文章,对任何不恰当的风格表示抱歉。
模型.py
class Coin(models.Model):
coin_name = models.CharField(max_length=100,blank=True)
class Data(models.Model):
coin = models.ForeignKey(Coin, related_name='data', on_delete=models.CASCADE,blank=True)
date = models.DateField(("Date"),blank=True)
open = models.FloatField(null=True, blank=True)
high = models.FloatField(null=True, blank=True)
low = models.FloatField(null=True, blank=True)
close = models.FloatField(null=True, blank=True)
class Meta:
unique_together = ('coin', 'date',)
ordering = ['date']
def __unicode__(self):
return '%d: %d %d %d %d' % (self.date, self.open, self.high,
self.low, self.close)
序列化程序.py
class DataSerializer(serializers.ModelSerializer):
class Meta():
model = models.Data
fields = ('coin_id','pk','id','date','open','high','low','close')
类 CoinSerializer(serializers.ModelSerializer): 数据 = DataSerializer(many=True)
class Meta:
model = models.Coin
fields = ('pk','id','coin_name', 'data')
def create(self, validated_data):
data = validated_data.pop('data')
coin = models.Coin.objects.create(**validated_data)
models.Data.objects.create(coin=coin, **data[0])
return coin
我的结果是这样的
{
"pk": 101,
"id": 101,
"coin_name": "ripple",
"data": [
{
"coin_id": 101,
"pk": 56,
"id": 56,
"date": "2016-12-25",
"open": 4036.0,
"high": 4101.0,
"low": 3983.0,
"close": 4065.0
}
]
},
and expect to consist lots of data objects which I will add by the time in existing coin object
{
"pk": 101,
"id": 101,
"coin_name": "ripple",
"data": [
{
"coin_id": 101,
"pk": 56,
"id": 56,
"date": "2016-12-25",
"open": 4036.0,
"high": 4101.0,
"low": 3983.0,
"close": 4065.0
}
{
"coin_id": 102,
"pk": 57,
"id": 57,
"date": "2016-12-26",
"open": 4065.0,
"high": 4189.0,
"low": 3967.0,
"close": 4075.0
}
...
...
]
},