51

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)
4
  • What exception are you receiving? Commented Oct 4, 2011 at 15:41
  • 2
    'dict' object has no attribute '_meta' Commented Oct 4, 2011 at 15:55
  • did you try it with queryset = myModel.objects.filter(foo_icontains=bar).values('foo.f1', 'foo.f2', 'foo.f3')? Commented Oct 4, 2011 at 16:05
  • possible duplicate of Converting a django ValuesQuerySet to a json object Commented Oct 4, 2011 at 16:05

6 Answers 6

61

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Finally, this helped me which I want the Queryset to be converted to JSON and then returned to the template.
@Kyle_397 . not sure you need this for sending queryset to your template. I think Django is able to handle a raw queryset. On the other hand, eg. Celery (or its broker in my case) is not
42

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.

8 Comments

Yes I am aware that .values() returns a list, however simplejson.dumps gives me a jsondata is not JSON serializable, the ValuesQuerySet is in the form: [{'key1': 'value1', 'key2': 'value2'}]
Yes, it depends on what data looks like, the first example from the linked answer is what you are looking for.
@bash- just call list() on it first.
Yes list(ValuesQuerySet) should return list which can then be serialized with simplejson.
@rebus thanks, it didn't work before because there was a DecimalField and it couldn't be serialized
|
26

Make list from objectQuerySet:

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

4 Comments

This was the quickest and simplest solution for me. I appended JsonResponse(data_ready_for_json, safe=False) and it worked perfectly in an Ajax call.
I had similar problem. Above solution of using list(queryset) worked very well. Thanks Max!
This works like a charm!!!
Also, you have the chance to manipulate the list before returning it, which might be very convenient
6

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})

1 Comment

Why do you serialize() and then loads() just to have the JsonResponse serialize the list again. This is extra, unnecessary work.
3

Just cast to dict every item and create json with json.dumps:

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

Comments

0

Try this:

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.