我刚刚开始为Django开发并使用Django REST Framework和基于类的视图构建API。我正在寻找一种方法来组合模型,根据时间对它们进行排序,然后将字段的子集返回到附加了表名的API。
目前我有以下内容:
views.py
class RunLog(APIView):
"""
List log for a specific run sorted in reverse chronological order
"""
def get(self, request, run_id, format=None):
# Combine and sort based on time (decreasing)
result_list = sorted(chain(Output.objects.filter(run=run_id),
Downtime.objects.filter(run=run_id)),
key=attrgetter('start_time'), reverse=True)
// Replace this with serializer??
response = Response(serializers.serialize('json', result_list), status=status.HTTP_200_OK)
return response
models.py
class Output(models.Model):
start_time = models.DateTimeField(default=datetime.now)
value = models.FloatField()
run = models.ForeignKey(Run, blank=True, null=True)
def __unicode__(self):
return str(self.id)
class Downtime(models.Model):
start_time = models.DateTimeField(default=datetime.now)
end_time = models.DateTimeField(null=True, blank=True)
reason = models.CharField(max_length=500)
run = models.ForeignKey(Run, blank=True, null=True)
我得到以下JSON:
"[{\"model\": \"app.downtime\", \"pk\": 91, \"fields\": {\"start_time\": \"2016-07-20T14:46:21Z\", \"end_time\": null, \"reason\": \"reason1\", \"run\": 71}}, {\"model\": \"app.downtime\", \"pk\": 101, \"fields\": {\"start_time\": \"2016-07-20T14:46:21Z\", \"end_time\": null, \"reason\": \"reason2\", \"run\": 71}}]"
我想用以下JSON格式序列化这些数据:
[
{
"id": 231,
"type": "speed",
"description": "Some description",
"time": "2016-07-21T21:26:26Z"
}
]
**Where type is the database table and description is concatenated columns from a model.
我看过文档和this similar question没有任何运气。
答案 0 :(得分:0)
正如IanAuld在评论中所建议的那样 - ModelObj._meta.db_table得到了表的名称。然后我在views.py中创建了一个排序的字典列表:
hdfs dfs -put opt/ibm/labfiles/README.md /user/root/input/tmp/
serializers.py:
speedList = Speed.objects.filter(run=run_id)
type = Speed._meta.db_table.split('_', 1)[1]
type = type[0].upper() + type[1:]
for speed in speedList:
description = "Speed change to %.2f (units)" % speed.value
logList.append({'id':speed.id, 'type':type, 'description':description, 'time':speed.start_time})
# Sort list by decreasing time
resultList= sorted(logList, key=itemgetter('time'), reverse=True)
serializer = LogSerializer(resultist, many=True)
return Response(serializer.data)