如何在 Django 中序列化 RawQuerySet?
我面临的问题是需要序列化 RawQuerySet。它没有值函数。我还给每个对象添加了一个小数注释,它是一个字段的计数。
示例代码:
cow_query = """SELECT cow.* (count(leg.id) / 4) as 'percentage' FROM cow JOIN leg ON leg.cow_id = cow.id;"""
cows = Cow.objects.raw(cow_query)
json = simplejson.dumps(cows) # this will not work
return HttpRepsonse(json)
序列化的最佳方法是什么。 我想要用注释序列化奶牛对象属性。最简单的可能只是将所有内容转换为字典和列表等,然后调用 simplejson.dumps,但这可能不是最有效的?
更新: 只是尝试使用 http://docs.djangoproject.com/en/dev /topics/serialization/#id2 但这不会将百分比添加到 json 结果中。
I am facing the problem that I need to serialize a RawQuerySet. It doesn't have the values function. I also added a decimal an annotation to every object, which is a count of a field.
Example code:
cow_query = """SELECT cow.* (count(leg.id) / 4) as 'percentage' FROM cow JOIN leg ON leg.cow_id = cow.id;"""
cows = Cow.objects.raw(cow_query)
json = simplejson.dumps(cows) # this will not work
return HttpRepsonse(json)
What is the best way to serialize it.
I want the cow object attributes serialized with the annotation. The simplest is probably just convert everything to dict and lists etc and than call simplejson.dumps, but this will maybe not be the most efficient?
UPDATE:
Just tried to use the http://docs.djangoproject.com/en/dev/topics/serialization/#id2 but this will not add the percentage to the json result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
simplejson.dumps([dict(cow.__dict__) forow inows])
怎么样?如果您的Cow
模型只有简单的字符串或整数值,这应该可以工作,否则您需要手动处理更复杂的类型(例如,DateTimeField
需要是unicode
-ed for simplejson)。How about
simplejson.dumps([dict(cow.__dict__) for cow in cows])
? If yourCow
model only has simple string or integer values this should work, otherwise you'll need to handle your more complex types manually (e.g.,DateTimeField
need to beunicode
-ed for simplejson).