2017-05-30 25 views
0

我有像这样一个Django模型:Django的休息字段分组和定制

class Floor(models.Model): 
    name = models.CharField(max_lenght =100) 

class Point(models.Model): 
    created_at  = fields.UnixDateTimeField(auto_now_add=True) 
    updated_at  = fields.UnixDateTimeField(auto_now=True) 
    floor   = models.ForeignKey(Floor) 
    device   = models.CharField(max_lenght=100) 

creates_at的updated_at只是带有时间戳的自定义字段。

所以,我需要像点发送请求/开始= X,结束= Y,时间片= Z,其中x? - 是启动时间戳,Y - 结束时间戳,Z - 时间片在这一时期。例如,如果x是一天的开始,y是一天,z是3600?我将有24片,并希望有JSON像这样:

{ 
    floor_id: floor_id 
    slice: first timestamp of first slice 
    count: count of devices in this slice 
}, 
{ 
    floor_id: floor_id 
    slice: first timestamp of second slice 
    count: count of devices in this slice 
}, 
... 

Propably,我需要定制我的串行器,使用Django过滤器和写spetial鉴于此目的,但我不知道怎样把它一起

UPD:好吧,我定制我的落地式串行器,现在它看起来像:

class FloorWithTPCountSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Floor 
     fields = ('id', 'count') 

    count = serializers.SerializerMethodField('get_tp_count') 

    def get_tp_count(self, obj): 
     return obj.trackpoint_set.values('tag').distinct().count() 

而且没有我recive JSON,如:

{ 
    "id": 28, 
    "count": 3 
}, 
{ 
    "id": 35, 
    "count": 1 
}, 

我可以建议,我需要在此序列化类中获取查询字符串参数,并声明在时间片内计算点的方法。那么,我如何才能在序列化类中得到querydict?

+0

你的问题不是很清楚。请求**指向/?start = x,end = y,timeslice = z **做什么?什么是开始,结束和时间片? –

+0

哦,我很抱歉,我纠正了它。 –

+0

可以肯定的是,您想要获取在开始和结束之间创建的所有点的列表,并将它们组合在一些时间片中,其中时间片是以秒为单位的时间段? –

回答

0

好吧,正如我早期建议的关键是在序列化器定制。我必须为所需的JSON结构声明自定义方法。 这里是我的解决方案:

class FloorWithTPCountSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Floor 
     fields = ('id', 'results') 

    results = serializers.SerializerMethodField('get_tp_start') 

    def get_tp_start(self, obj): 
     query_params = self.context.get("request").query_params 
     aggregations = {'hour':3600, 'day':86400, 'week':604800} 
     if 'start' in query_params and 'end' in query_params: 
      st_tm = int(query_params.get('start')) 
      en_tm = int(query_params.get('end')) 
      if 'aggregation' in query_params: 
       aggregation_value = query_params.get('aggregation') 
       aggregation = aggregations.get(aggregation_value) 
      else: 
       aggregation = en_tm - st_tm 
      trackpoint_set = obj.trackpoint_set 
      st = [{'count': trackpoint_set.filter(created_at__gte=ts, created_at__lt=ts + aggregation).values(
       'tag').distinct().count(), 'timestamp': ts} for ts in range(st_tm, en_tm, aggregation)] 

     else: 
      st = None 
     return st 

Ofcourse,它仍然缺乏由querstring一致性一些检查,但我可以获取JSON形式,因为我需要。 ? 例如,请求

tpfloors /启动= 1496188800 &末= 1496275199 &聚集=天

我能得到这样的事情:

{ 
    "id": 49, 
    "results": [ 
     { 
     "count": 3, 
     "timestamp": 1496188800 
     } 
    ] 
    }, 

最好的问候。