【发布时间】:2019-09-17 05:25:06
【问题描述】:
我有一个这样的嵌套结构:
class Student(object):
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
class Address(object):
def __init__(self, street, pcode, another_obj):
self.street = street
self.postal_code = pcode
self.another_obj = another_obj
class AnotherObject(object):
def __init__(self):
self.someattr = 'some_init_value'
# Now i amm going to save data like this
another_obj = AnotherObject()
address = Address('xyz', 'xyz', another_obj)
obj = Student('abc', 32, address)
对象obj 是一个类的实例。我正在做collection.insert_one(obj)。通常,我会执行 obj.dict 来获取与 pymongo 兼容的类实例的“dict”,但它也不会将嵌套对象转换为 dict。 这里的问题是“地址”和“some_other_object”也是一些其他类实例,这会导致 bson.errors.InvalidDocument 插入时出现异常。
有没有办法将嵌套类实例/文档(地址和 some_other_object)转换为 dict 或 mongodb 可接受的任何其他类型。
我用于mongodb通信的包是pymongo v3.9.0。
错误为 TypeError:
document 必须是 dict、bson.son.SON 的实例, bson.raw_bson.RawBSONDocument,或继承自的类型 集合.MutableMapping
【问题讨论】:
-
显示课程。请阅读how to ask