简体   繁体   中英

How to serialize Django queryset.values() into json?

I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a .values set I get an exception:

'dict' object has no attribute '_meta'

This is my code:

queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = serializers.serialize('json', queryset, ensure_ascii=False)

As other people have said, Django's serializers can't handle a ValuesQuerySet. However, you can serialize by using a standard json.dumps() and transforming your ValuesQuerySet to a list by using list() . If your set includes Django fields such as Decimals, you will need to pass in DjangoJSONEncoder . Thus:

import json
from django.core.serializers.json import DjangoJSONEncoder

queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = json.dumps(list(queryset), cls=DjangoJSONEncoder)

Django serializers can only serialize queryset, values() does not return queryset rather ValuesQuerySet object. So, avoid using values() . Rather, specifiy the fields you wish to use in values() , in the serialize method as follows:

Look at this SO question for example

objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
data = serializers.serialize('json', list(objectQuerySet), fields=('fileName','id'))

Instead of using objectQuerySet.values('fileName','id') , specify those fields using the fields parameter of serializers.serialize() as shown above.

从 objectQuerySet 创建列表:

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

My solution, It's work fine

from django.core.serializers import serialize
import json

permission_list = Permission.objects.all().order_by('-id')
permission_serialize= json.loads(serialize('json', permission_list))
return JsonResponse({'data': permission_serialize})

只需转换为 dict 每个项目并使用 json.dumps 创建 json:

json.dumps([dict(item) for item in SomeModel.objects.all().values('id', 'title')])

Try this:

queryset = myModel.objects.filter(foo_icontains=bar)
serialized_q = serializers.serialize(queryset, many = True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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