python - 如何将 Django 对象转换为 json?
问题描述
嗨,我正在尝试将 Django 查询集对象转换为 JSON,但每次尝试使用 python JSON 模块执行此操作时,都会收到此错误:“TypeError:QuerySet 类型的对象不是 JSON 可序列化的”。这是 Django 对象:titles = Queries.objects.values('Topic').distinct().
这是它返回的内容 `<QuerySet [{'Topic': 'Phone or Web'}, {'Topic': 'Time or Money'}, {'Topic': 'Power or Wisdom' }, {'Topic': '奢华还是露营!'}]>。
现在,即使我尝试使用 django 序列化程序尝试解决此问题,我也会收到此错误:“AttributeError:'dict' 对象没有属性'_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)
解决方案
QuerySet 中的对象是什么,它仍然是一个 QuerySet。我的猜测是:您不想序列化您的 QuerySet,而是序列化其中的内容和对象。也就是说:您需要解压缩 QuerySet 并将序列化应用于其中的每个对象。
例子:
from django.contrib.auth.models import User
allUsers = User.objects.all() # QuerySet: allUsers
# apply your operation on each object in QuerySet (users) like this:
serializedData = [ json.dumps({'usrname': user.username,
'mail': user.email}) for user in allUsers]
您的序列化数据集现在位于 serializedData 中。问题是,你想做这样的事情:
serializedData = [ json.dumps(user) for user in allUsers ]
但是对于 json.dumps() 和您的对象(在此示例中为 User 对象),没有免费午餐之类的东西。你有两个选择:
(1) 像上面的例子 {'usrname': user.username......}) 或
(2) 您需要在用户对象“class UserEncoder(JSONEncoder):”的情况下定义一个“class ObjectClassNameEncoder(JSONEncoder):”,这更“复杂”。底线:您必须寻找的路径:JSONEncoder。
推荐阅读
- vue.js - vuejs 错误修复调试/部署查询
- python - 如何创建具有衍生进程的 MPI 组?
- javascript - 与 include 一起使用时,Sequelize 返回空值
- python - 删除列表中重复的元组和列表
- python-2.7 - 如何使用python2.7将逗号分隔的字典包含在列表[]中
- php - 在 Laravel 测试中模拟控制器的接口依赖
- c++ - Opencv c ++ stereoBM视差图距离有限
- mysql - 可以使用 COUNT 查询吗?
- azure-active-directory - 事件网格订阅者的 AAD 身份验证
- python - Django 查询集 - 从 json 对象转换