简体   繁体   English

将 django ValuesQuerySet 转换为 json object

[英]Converting a django ValuesQuerySet to a json object

I'm trying to use the ValuesQuerySet feature in Django to limit the number of fields returned from query to only those I need.我正在尝试使用 Django 中的 ValuesQuerySet 功能将查询返回的字段数限制为我需要的字段数。 I would like to serialize this data set a JSON object However, Django keeps throwing an error.我想将此数据集序列化为 JSON object 但是,Django 不断抛出错误。 Below I've included my code and the error I receive:下面我包含了我的代码和我收到的错误:

objectList = ConventionCard.objects.values('fileName','id').filter(ownerUser = user)
data = serializers.serialize('json', objectList)
return HttpResponse(data, mimetype='application/javascript')

The Error:错误:

Exception Type:     AttributeError
Exception Value:    'dict' object has no attribute '_meta'
Exception Location:     C:\Python27\lib\site-packages\django\core\serializers\base.py in serialize, line 41

Thanks !谢谢 !

Cast the ValuesQuerySet to a list first:首先将 ValuesQuerySet 转换为列表:

query_set = ConventionCard.objects.values('fileName','id').filter(ownerUser = user)

list(query_set)

Removing the values call as suggested by ars causes the manager to pull all columns from the table, instead of only the two you need.按照 ars 的建议删除values调用会导致经理从表中提取所有列,而不仅仅是您需要的两列。

Try subsetting the fields in your values list through the serialize method using a QuerySet instead:尝试使用 QuerySet 通过serialize方法对值列表中的字段进行子集化:

from django.core import serializers
objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
data = serializers.serialize('json', objectQuerySet, fields=('fileName','id'))

I continued to get a dict object has no attribute _meta error when using the list() method above.使用上面的list()方法时,我继续得到一个dict object has no attribute _meta错误。 However I found this snippet that does the trick但是我发现这个片段可以解决问题

def ValuesQuerySetToDict(vqs):
    return [item for item in vqs]

# Usage
data = MyModel.objects.values('id','title','...','...')
data_dict = ValuesQuerySetToDict(data)
data_json = simplejson.dumps(data_dict)

Just to add a few details I've found:只是添加一些我发现的细节:

When I tried @ars answer specifying the fields, like:当我尝试@ars answer指定字段时,例如:

s_logs = serializers.serialize("json", logs, fields=('user', 'action', 'time'))

I get this:我明白了:

[{"pk": 520, "model": "audit.auditlog", "fields": {"user": 3, "action": "create", "time":"2012-12-16T12:13:45.540"}}, ... ]

Which was not a simple serialization of the values as I wanted it.这不是我想要的值的简单序列化。

So I tried the solution proposed by @Aaron, converting the valuesqueryset to a list, which didn't work the first time because the default encoder cannot deal with floats or datetime objects.所以我尝试了@Aaron 提出的解决方案,将 valuesqueryset 转换为列表,第一次没有工作,因为默认编码器无法处理浮点数或日期时间对象。

So I used @Aaron solution but using the JSON encoder that is used by django's serializer (DjangoJSONEncoder) by passing it as a kwarg to simplejson.dumps() , like this:因此,我使用了@Aaron 解决方案,但使用了 django 的序列化程序 (DjangoJSONEncoder) 使用的 JSON 编码器,方法是将其作为 kwarg 传递给simplejson.dumps() ,如下所示:

s_logs = list(logs.values('user', 'ip', 'object_name', 'object_type', 'action', 'time'))

return HttpResponse(simplejson.dumps( s_logs, cls=DjangoJSONEncoder ), mimetype='application/javascript')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM