在Django中向db响应添加一些数据

时间:2013-10-16 19:53:48

标签: django json

客户端从两个表中获取数据。以下是文件views.py中的代码:

...
dbdataA = TableA.objects.filter(user=user)
dbdataB = TableB.objects.filter(user=user).order_by("field1")
result_list = list(chain(orders, alldata))
msg = serializers.serialize("json", result_list, fields=("field1","field2","field3","field4"), use_natural_keys=True)
return HttpResponse(msg)

我需要添加一个带有当前时间的var来响应。怎么做?

UPD: 传递给chain(orders,alldata,...)的任何数据都会给出错误“'str'对象在字符串”msg = serializers.serialize ...“中没有属性'_meta'”。也许是因为chain()除了iterable之外不能接受任何数据,但是(time.asctime(time.localtime())是不可迭代的?

1 个答案:

答案 0 :(得分:2)

将变量添加到您的result_listfields列表中。

import time
result_list = list(chain(orders, alldata,
                         (time.asctime(time.localtime()),))
                  ) #or other time function
msg = serializers.serialize("json", result_list,
                            fields=("field1", "field2", "field3", "field4", "time"),
                            use_natural_keys=True)

或者,如果您不想将时间添加到JSON对象中,HTTPResponse(msg) already sets Http Response标头中的Date参数。