Reputation: 15573
I have a django model called ServiceSubCategory
and I want to create a JSON list of its primary key values using Python.
I have tried this:
idDic=[obj.as_json for obj in ServiceSubCategory.objects.values_list('id',flat=True)]
But I'm getting this error:
int
object has no attributeas_json
I'm doing this because I'm gonna append another JSON to this later.
So how could I create a JSON out of my models primery Keys?
Update
I tried
id_json = json.dumps(ServiceSubCategory.objects.values_list('id',flat=True))
And I'm getting a new error:
[1,2,3,4,5,6,7,8,9,10] is not JSON serializable
And this is the traceback:
Traceback: File "/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/salimi/salimi/views.py" in service 61. idDic=json.dumps(ServiceSubCategory.objects.values_list('id',flat=True)) File "/usr/lib/python2.7/json/init.py" in dumps 243. return _default_encoder.encode(obj) File "/usr/lib/python2.7/json/encoder.py" in encode 207. chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python2.7/json/encoder.py" in iterencode 270. return _iterencode(o, 0) File "/usr/lib/python2.7/json/encoder.py" in default 184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /service/1/ Exception Value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is not JSON serializable
Upvotes: 0
Views: 2198
Reputation: 1958
This should do the trick:
import json
json.dumps(list(ServiceSubCategory.objects.values_list('id', flat=True)))
values_list
returns an instance of django.db.models.query.ValuesListQuerySet
which does not have a default JSON serializer (it's just a QuerySet, no database request is made so far). However, you can transform it into a list object before.
import json
values_list_object = ServiceSubCategory.objects.values_list('id', flat=True))
list_object = list(values_list) # querying the database
json.dumps(list_object)
Upvotes: 3
Reputation: 87084
Update
It looks like ServiceSubCategory.objects.values_list('id', flat=True)
might return a generator. In that case you can consume the generator using list()
:
import json
json.dumps(list(ServiceSubCategory.objects.values_list('id', flat=True)))
Wouldn't this do the trick?
import json
json.dumps(ServiceSubCategory.objects.values_list('id', flat=True))
Since ServiceSubCategory.objects.values_list
is already a list it can be dumped directly to JSON. There is no need to use a list comprehension.
Upvotes: 1
Reputation: 59184
You can simply write the following:
import json
id_json = json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))
Upvotes: 1