简体   繁体   English

Django 查询集:从查询集构建字典,具有公共元素

[英]Django queryset: Build a dictionary from a queryset, with common elements

I'm trying to construct a dictionary from my database, that will separate my data into values with common time stamps.我正在尝试从我的数据库构建一个字典,它将我的数据分成具有公共时间戳的值。

data_point:
    time: <timestamp>
    value: integer

I have 66k data points, out of which around 7k share timestamps (meaning the measurement was taken at the same time.我有 66k 个数据点,其中大约 7k 个共享时间戳(意味着测量是同时进行的。

I need to make a dict that would look like:我需要制作一个看起来像这样的字典:

{
  "data_array": [
    {
      "time": "2018-05-11T10:34:43.826Z",
      "values": [
        13560465,
        87856595,
        78629348
      ]
    },
    {
      "time": "2018-05-11T10:34:43.882Z",
      "values": [
        13560689,
        78237945,
        92378456
      ]
    }
  ]
}

There are other keys in the dictionary, but I'm just having a bit of a struggle with this particular key.字典中还有其他键,但我对这个特定键有点困难。

The idea is, look at my data queryset, and group up objects that share a timestamp , then add a key "time" to my dict, with the value being the timestamp , and an array "values" with the value being a list of those data.value objects这个想法是,查看我的数据查询集,并将共享时间戳的对象分组,然后在我的字典中添加一个键“时间”值为时间戳数组“值” ,值为一个列表那些data.value对象

I'm not experienced enough to build this without looping a lot and probably being very innefficient.我没有足够的经验来构建它而不会循环很多并且可能非常低效。 Some kind of "while timestamp doesn't change: append value to list", though I'm not sure how to go about that either.某种“虽然时间戳不会改变:将值附加到列表”,但我也不知道如何去做。

Ideally, if I can do this with queries (should be faster, right?) I would prefer that.理想情况下,如果我可以通过查询来做到这一点(应该更快,对吗?)我更喜欢这样。

Why not use collections.defaultdict ?为什么不使用collections.defaultdict

from collections import defaultdict

data = defaultdict(list)   

# qs is your queryset
for time, value in qs.values_list('time', 'value'):
    data[time].append(value)

In that case data looks like:在这种情况下,数据如下所示:

{
    'time_1': [
        value_1_1,
        value_1_2,
        ...
    ],
    'time_2': [
        value_2_1,
        value_2_2,
        ...
    ],
    ....
}

at this point you can build any output format you want此时您可以构建您想要的任何输出格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM