如何在ValueQuerySet(Django)中添加额外的字段?

时间:2017-05-19 08:09:08

标签: json django serialization markerclusterer

基本上,我想将query_set转换为JSON。但是我还想在query_set中添加一个像size = some number这样的字段,这个字段在query_set属性中不存在(它是计算属性)。你能告诉我怎么做吗?

    query_set = PotholeCluster.objects.all().values('bearing', 'center_lat', 'center_lon', 'grid_id')
    return JsonResponse(list(query_set), safe=False)

我尝试了下面的代码。它有效,但我想知道是否有更清洁的方法来做到这一点。

    query_set = PotholeCluster.objects.all()
    response_list = []
    for pc in query_set:
        d = {}
        d['bearing'] = pc.get_bearing()
        d['center_lat'] = pc.center_lat
        d['center_lon'] = pc.center_lat
        d['grid_id'] = pc.grid_id
        d['size'] = pc.pothole_set.all().count()
        response_list.append(d)
        serialized = json.dumps(response_list)
return HttpResponse(serialized, content_type='application/json')


class PotholeCluster(models.Model):
    center_lat = models.FloatField(default=0)
    center_lon = models.FloatField(default=0)
    snapped_lat = models.FloatField(default=0)
    snapped_lon = models.FloatField(default=0)
    size = models.IntegerField(default=-1)
    # avgspeed  in kmph
    speed = models.FloatField(default=-1)
    # in meters
    accuracy = models.FloatField(default=-1)
    # avg bearing in degree
    bearing = models.FloatField(default=-1)
    grid = models.ForeignKey(
        Grid,
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )

    def __str__(self):
        raw_data = serialize('python', [self])
        output = json.dumps(raw_data[0]['fields'])
        return "pk = {}|{}".format(self.id, output)

    def get_bearing(self):
        if self.bearing != -1:
            return self.bearing
        potholes = self.pothole_set.all()
        bearings = [pothole.location.bearing for pothole in potholes]
        bearings.sort()
        i = 0
        if bearings[-1] >= 350:
            while bearings[-1] - bearings[i] >= 340:
                if bearings[i] <= 10:
                    bearings[i] += 360
                    i += 1
        self.bearing = sum(bearings) / len(bearings) % 360
        self.save()
        return self.bearing

    def get_size(self):
        if self.size != -1:
            return self.size
        self.size = len(self.pothole_set.all())
        self.save()
        return self.size

0 个答案:

没有答案