如何将sql查询序列化为json?

时间:2014-11-04 21:33:37

标签: json django django-serializer

我正在尝试将sql查询序列化为json:

cursor.execute("""SELECT b.tonode, n.name, b.fromnode FROM zusers u JOIN znode n
                                                    ON u.code = n.created_by
                                                JOIN zbond b
                                                    ON b.code = n.code
                                                WHERE u.userid = %s""", [user_id] )

data = serializers.serialize('json', rows, fields = ('id', 'name', 'parent'))

但它不起作用。是否可以序列化不是模型的对象,而是sql查询?

4 个答案:

答案 0 :(得分:2)

基于doc

  

实际上,第二个参数可以是产生Django模型实例的任何迭代器,但它几乎总是一个QuerySet

试试这个:

query = """SELECT b.tonode, n.name, b.fromnode FROM zusers u JOIN znode n
                                                    ON u.code = n.created_by
                                                JOIN zbond b
                                                    ON b.code = n.code
                                                WHERE u.userid = %s"""%user_id

data = serializers.serialize('json', YourModel.objects.raw(query), fields=('id', 'name', 'parent'))

答案 1 :(得分:1)

试试这段代码:

cursor = connection.cursor()
cursor.execute("""SELECT b.tonode, n.name, b.fromnode FROM zusers u JOIN znode n ON u.code = n.created_by JOIN zbond b ON b.code = n.code WHERE u.userid = %s""", [user_id])
rows = cursor.fetchall()
result = []
keys = ('id','name','parent',)
for row in rows:
    result.append(dict(zip(keys,row)))
json_data = json.dumps(result)
return HttpResponse(json_data, content_type="application/json")

答案 2 :(得分:0)

尝试此代码

    cursor = connection.cursor()
    cursor.execute("""SELECT b.tonode, n.name, b.fromnode FROM zusers u JOIN znode n ON u.code = n.created_by JOIN zbond b ON b.code = n.code WHERE u.userid = %s""", [user_id])
    cursor.fetchall()
    json_data = dictfetchall(cursor)
    return HttpResponse(json_data, content_type="application/json")

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
     columns = [col[0] for col in cursor.description]
     return [
         dict(zip(columns, row))
         for row in cursor.fetchall()
     ]

答案 3 :(得分:0)

cursor = connection.cursor()
cursor.execute("""SELECT b.tonode, n.name, b.fromnode FROM zusers u JOIN znode n ON u.code = n.created_by JOIN zbond b ON b.code = n.code WHERE u.userid = %s""", [user_id])
rows = cursor.fetchall()
result = []
keys = ('id','name','parent',)
for row in rows:
    result.append(dict(zip(keys,row)))
json_data = json.dumps(result)
return HttpResponse(json_data, content_type="application/json")