【发布时间】:2020-12-23 23:06:00
【问题描述】:
您好,我正在尝试将 Django 查询集对象转换为 JSON,但每次尝试使用 python JSON 模块执行此操作时,我都会收到此错误:“TypeError:QuerySet 类型的对象不是 JSON 可序列化的”。这是 Django 对象:titles = Queries.objects.values('Topic').distinct().,这是它返回的内容 `
现在,即使我尝试使用 django 序列化程序来尝试解决此问题,我也会收到此错误:“AttributeError: 'dict' object has no attribute '_meta'。”谁能帮我解决这个问题?这是我在这两种情况下的代码。
django 序列化器情况的代码:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Queries
import json
from django.core.serializers import json
from django.core import serializers
def data_json():
titles = Queries.objects.values('Topic').distinct()
titles_json = serializers.serialize('json', titles)
with open('topic.json', 'w') as file:
data = json.dumps(titles_json)
print(data, file=file)
print(titles)
def index(request, query_title):
queries = Queries.objects.all()
page = Queries.objects.filter(Topic=str(query_title))
# print(page)
data_json()
return render(request, 'Querie/index.html', {'queries': page})
当我使用常规 json 模块时,我的代码看起来像这样,所以 data_json 函数是这样的:
import json
def data_json():
titles = Queries.objects.values('Topic').distinct()
with open('topic.json', 'w') as file:
data = json.dumps(titles)
print(data, file=file)
【问题讨论】:
-
这能回答你的问题吗? Django Serializing of ValueQuerySet
-
不,说实话,我不确定我是否理解所显示的答案要做什么。
-
答案表明您不能序列化一个
ValueQuerySet(与您的情况相同),它是一个可迭代的包含dict对象,使用 Django 序列化器 -
好吧,那我怎么把它转换成 JSON?
-
你试过
data = json.dumps(list(titles))吗?
标签: python json django django-models django-views