欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AttributeError: 'tuple' object has no attribute '_meta' 解决方案

程序员文章站 2022-05-27 11:51:22
...

查看错误信息:元组(tuple)对象中没有‘_meta’这个属性?
下面是我的代码

#导入json模块
import json
from django.core import serializers
from django.http import JsonResponse

def ajax_jz(request):
        #获取数据库连接,并获取游标
        cur = connection.cursor()
        #原生SQl语句(连表查询(没有主外键关系))
        sql ='select j.id,h.GPS,j.SystemStatus,j.YuLiu3 from tower_project_jizhan j inner join tower_project_hjinformation h on j.SheBei_Code= h.SheBei_Code'
        #执行命令
        cur.execute(sql)
        #返回查询到的所有数据
        resultData = cur.fetchall()
        for item in resultData:
            print(item)
        #对数据进行序列化,并转成JSON
        ajax_bmsValue = serializers.serialize("json", resultData)
        #返回数据
        return HttpResponse(ajax_bmsValue)

能够查询到数据,但把数据进行序列化时就出错了;是传递的类型不对,还是什么?django的序列化类位于django.core下面的serializers文件夹里面,base.py文件里面定义了序列器和反序列器的基类以及一些异常,init.py文件定义了如何根据格式来选择对应的序列器等内容
init.py

def get_deserializer(format):
    if not _serializers:
        _load_serializers()
    if format not in _serializers:
        raise SerializerDoesNotExist(format)
    return _serializers[format].Deserializer


def serialize(format, queryset, **options):
    """
    Serialize a queryset (or any iterator that returns database objects) using
    a certain serializer.
    """
    s = get_serializer(format)()
    s.serialize(queryset, **options)
    return s.getvalue()

解决方案:
import json

return JsonResponse(json.dumps(data), safe=True)

def ajax_jz(request):
        #获取游标
        cur = connection.cursor()
        sql ='select j.id,h.GPS,j.SystemStatus,j.YuLiu3 from tower_project_jizhan j inner join tower_project_hjinformation h on j.SheBei_Code= h.SheBei_Code'
        cur.execute(sql)
        resultData = cur.fetchall()
        for item in resultData:
            print(item)
         #采用json.dumps
        return HttpResponse(json.dumps(resultData))
        #关闭连接
        cur.close()