我正在编写一个API,用于查询基于Cassandra 2.1.2的数据库并以JSON格式返回结果。我正在使用cqlengine。
这是简化的架构 -
class Checkins(Model):
Model.__comment__ = "Table mapping for submit datastore"
changelist = columns.Integer (primary_key= True) # Changelist number
checkin_date = columns.DateTime() # Submit time
stream_name = columns.Ascii (primary_key= True) # Stream-name
creator = columns.Ascii () # Creator
我的查询是
clobj = Checkins.objects(changelist=changelist).get()
如何将结果集转换为json格式?
答案 0 :(得分:0)
您可以在cqlengine 0.12中创建dictionaries from models。从那里你可以使用json模块获得JSON格式。你必须要小心,因为datetimes不是json可序列化的。因此,您需要先将其转换为字符串(或者查看this question以了解修复日期时间序列化问题的其他方法)。
import json
clobj = Checkins.objects(changelist=changelist).get()
clobj_dict = dict(clobj_dict)
clobj_dict['checkin_date'] = str(clobj_dict['checkin_date'])
json_string = json.dumps(clobj_dict)
或者您可以将其添加为类
上的属性import json
class Checkins(Model):
# Define your model as before
# ...
@property
def json(self):
# Perform the same thing as before.
json_dict = dict(self)
json_dict['checkin_date'] = str(json_dict['checkin_date'])
return json.dumps(clobj_dict)
# Just call the property.
clobj = Checkins.objects(changelist=changelist).get()
json_string = clobj.json