I am trying to convert the ObjectId
and ISODate
to string representations while querying from MongoDB database.
def mongo_to_dict(obj, exclude_fields):
return_data = []
if obj is None:
return None
if isinstance(obj, Document):
return_data.append(("_id", str(obj.id)))
for field_name in obj._fields:
if field_name in exclude_fields:
continue
if field_name in ("id",):
continue
data = obj._data[field_name]
if isinstance(obj._fields[field_name], ListField):
return_data.append((field_name, list_field_to_dict(data)))
elif isinstance(obj._fields[field_name], EmbeddedDocumentField):
return_data.append((field_name, mongo_to_dict(data, [])))
elif isinstance(obj._fields[field_name], DictField):
return_data.append((field_name, data))
else:
return_data.append((field_name, mongo_to_python_type(obj._fields[field_name], data)))
return dict(return_data)
def list_field_to_dict(list_field):
return_data = []
for item in list_field:
if isinstance(item, EmbeddedDocument):
return_data.append(mongo_to_dict(item, []))
else:
return_data.append(mongo_to_python_type(item, item))
return return_data
def mongo_to_python_type(field, data):
if isinstance(field, DateTimeField):
return time.mktime(data.timetuple()) * 1000
elif isinstance(field, ComplexDateTimeField):
return field.to_python(data).isoformat()
elif isinstance(field, StringField):
return str(data)
elif isinstance(field, FloatField):
return float(data)
elif isinstance(field, IntField):
return int(data)
elif isinstance(field, BooleanField):
return bool(data)
elif isinstance(field, ObjectIdField):
return str(data)
elif isinstance(field, DecimalField):
return data
else:
return str(data)
class Portfolio(Document):
meta = {'collection': 'Portfolios'}
PortfolioName = StringField()
LastUpdateDate = DateTimeField(default=datetime.datetime.now())
RecentActivity = ListField(default=[])
def to_dict(self):
return mongo_to_dict(self, [])
Now when i create a Portfolio Object like this
a = Portfolio(PortfolioName='BB Visa').save()
and when i try to get the to_dict()
repressentation for the object like a.to_dict()
, it works perfectly.
{'_id': '5581cf9129e457241a32e8f7', 'PortfolioName': 'BB Visa', 'RecentActivity': [], 'LastUpdateDate': 1434570641000.0}
But the problem is i want to_dict()
to operate on class level not object level.
So when i tried to define a custom queryset like this
class Portfolio(Document):
meta = {'collection': 'Portfolios'}
PortfolioName = StringField()
LastUpdateDate = DateTimeField(default=datetime.datetime.now())
RecentActivity = ListField(default=[])
@queryset_manager
def to_dict(self, queryset):
return mongo_to_dict(self, [])
Now running the following command Portfolio.to_dict()
generates error like below
Traceback (most recent call last):
File "/home/ajay/PycharmProjects/solveit/test.py", line 102, in <module>
print(Portfolio.to_dict())
File "/home/ajay/.pyenv/versions/3.4.3/lib/python3.4/site-packages/mongoengine/queryset/manager.py", line 43, in __get__
queryset = self.get_queryset(owner, queryset)
File "/home/ajay/PycharmProjects/solveit/test.py", line 83, in to_dict
return mongo_to_dict(self, [])
File "/home/ajay/PycharmProjects/solveit/test.py", line 28, in mongo_to_dict
data = obj._data[field_name]
TypeError: 'member_descriptor' object is not subscriptable
I understand that QuerySet Manager passes class into the function, thats why the error. How to solve this.
Actually I am not sure that it is right decision to define this as
@queryset_manager
cause according to documentationI suggest adding some separate utils function that takes queryset:
Or if you still want to have this as
@queryset_manager
then:Also there is a ready method of mongoengine Model objects
to_mongo
. You can try it like this:[obj.to_mongo() for obj in queryset]
. Is not it applicable?