AttributeError: 'tuple' object has no attribute '_meta' 解決方案
阿新 • • 發佈:2019-02-03
檢視錯誤資訊:元組(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()