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. I would like to serialize this data set a JSON object However, Django keeps throwing an error. 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\ in serialize, line 41

Thanks !

3/15/2019 12:02:26 PM

Accepted Answer

Try subsetting the fields in your values list through the serialize method using a QuerySet instead:

from django.core import serializers
objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
data = serializers.serialize('json', objectQuerySet, fields=('fileName','id'))
8/4/2016 1:01:51 PM

Cast the ValuesQuerySet to a list first:

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


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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow