Django Query Set into json object - python

Below I'm trying to get a query make is a json object, so that in my template using jQuery I can loop over it.
My View
from django.core import serializers
objectQuerySet = Recipient.objects.filter(incentiveid=incentive).values("mobile", "countryid")
data = serializers.serialize("json", objectQuerySet)
return render_to_response('smssend.html', context_instance=RequestContext(request))
I'm getting the following error.
Non-model object (<type 'dict'>) encountered during serialization
Request Method:
why?

#values() "returns dictionaries when used as an iterable" - https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values
I think you need python's json#dumps(dict) here

Related

How to handle 'dict' object has no attribute 'META'?

I'm trying to create a JSON response in a django project; but something goes wrong!
applications_list = []
for project in projects_list:
application_information = {
``` some keys and values ```
}
applications_list.append(application_information)
context = {'applications': applications_list}
return render(request, self.template_name, context)
But I got this error:
'dict' object has no attribute 'META'
Should be mentioned that keys and values of application_information are serialized. I also tried json.dumps() but didn't work.
I wonder what have been missed?
Sounds like you accidentally modified the request variable before you passed it to render call.
Check what happens with that variable in the code before the snippet you posted, or expand your question with additional code lines.

In Django, how do I serialize a QuerySet that returns a dict object (created with .values())

In Django 1.10 I am trying to serialize an QuerySet that I obtained from the following query:
events_in_period = Event.objects \
.filter(timestamp__gte=start_day,
timestamp__lte=end_day,
request__isnull=False,
name=EventType.COMPLETED) \
.annotate(date=TruncDay('timestamp')) \
.values('date') \
.annotate(completed_count=Count('id')) \
.order_by('date')
The main thing is the .values() statement that makes this statement return a QuerySet that contains a dict rather than a Django model instance.
Therefore the following calls to serialize it
from django.core import serializers
output = serializers.serialize('json', result)
fail with the following error:
AttributeError: 'dict' object has no attribute '_meta'
Any suggestions on serialization without omitting the .values() as I need them for brevity.
If you want to serialize the dict object into json, then you could import json,
import json
data = json.dumps(result)
The Django serializers are for Django model objects and QuerySets. That's why it's looking for a _meta field. 

How to Return an array of objects in a Django model

I'm using javascript (plus AngularJS and Restangular) to call a Django endpoint and retrieve an array of proposals. But I can't seem to get my Django syntax right.
How do I return and array of objects in a given Django model?
def proposal_api(request):
response = {}
response['proposal_list'] = Proposal.objects.all()
return response
The Django View above throws the following Attribute error: 'dict' object has no attribute 'status_code'
Once I receive the array of proposals from the above Django View (with IDs, names, questions, etc...) I'll use AngularJS to display everything.
You need to read up on writing views in the documentation. A view function should return an HTTP response object.
The simplest way would be to just use the HttpResponse object from Django like so
from django.core import serializers
from django.http import HttpResponse
def proposal_api(request):
response = {}
response['proposal_list'] = serializers.serialize("json", Proposal.objects.all())
return HttpResponse(response, content_type="application/json")
If you are building an API, however, I would strongly encourage you to checkout TastyPie or Django-Rest-Framework.

is not JSON serializable

I have the following ListView
import json
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return json.dumps(self.get_queryset().values_list('code', flat=True))
But I get following error:
[u'ae', u'ag', u'ai', u'al', u'am',
u'ao', u'ar', u'at', u'au', u'aw',
u'az', u'ba', u'bb', u'bd', u'be', u'bg',
u'bh', u'bl', u'bm', u'bn', '...(remaining elements truncated)...']
is not JSON serializable
Any ideas ?
It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.

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\base.py in serialize, line 41
Thanks !
Cast the ValuesQuerySet to a list first:
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.
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'))
I continued to get a dict object has no attribute _meta error when using the list() method above. 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:
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.
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:
s_logs = list(logs.values('user', 'ip', 'object_name', 'object_type', 'action', 'time'))
return HttpResponse(simplejson.dumps( s_logs, cls=DjangoJSONEncoder ), mimetype='application/javascript')

Categories

Resources