Reputation: 43
Trying to serialize a MongoDB cursor in Django
import json
from pymongo import json_util
results = json.dumps(results, default=json_util.default, separators=(',', ':'))
Where the original results
is something like
[{u'_id': ObjectId('4f7c0f34705ff8294a00006f'),
u'identifier': u'1',
u'items': [{u'amount': 9.99, u'name': u'PapayaWhip', u'quantity': 1}],
u'location': None,
u'timestamp': datetime.datetime(2012, 4, 4, 10, 7, 0, 596000),
u'total': 141.25}]
Edit: Obtained by using something like
from django.db import connections
connection = connections['default']
results = connection.get_collection('papayas_papaya')
results = results.find({
'identifier': '1',
})
Gives me
TypeError: <django_mongodb_engine.utils.DebugCursor object> is not JSON serializable
Does anyone know what I'm doing wrong?
Using json_util should serialize MongoDB documents, maybe my issue is that I'm trying to serliaze a cursor. (How do I get the document from the cursor? A simple tuple "cast"?)
Cheers!
Upvotes: 4
Views: 1289
Reputation: 2491
You should really be using Django's serialization system, or a pluggable JSON-serialization app at least.
Upvotes: 0
Reputation: 18653
Are you trying to serialize just one piece of data? If so, just change
results = results.find({
'identifier': '1',
})
to
results = results.find_one({
'identifier': '1',
})
(Although you really should make a distinction between your results and the variable representing your collection.)
If you are trying to serialize multiple pieces of data, you can keep the find
and then iterate through the cursor and serialize each piece of data.
serialized_results = [json.dumps(result, default=json_util.default, separators=(',', ':')) for result in results]
Upvotes: 5