Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 465
bash- Avatar asked Oct 04 '11 15:10

bash-


People also ask

How do you serialize a Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

How does Django get JSON data?

To receive JSON data using HTTP POST request in Python Django, we can use the request. body property in our view. to call json. oads with request.

How does Django define Queryset?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


3 Answers

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)
like image 147
Andre Gregori Avatar answered Oct 17 '22 22:10

Andre Gregori


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.

like image 38
Davor Lucic Avatar answered Oct 17 '22 21:10

Davor Lucic


Make list from objectQuerySet:

data_ready_for_json = list( ConventionCard.objects.filter(ownerUser = user).values('fileName','id') )
like image 19
Max Avatar answered Oct 17 '22 21:10

Max