python convert object into json for mongodb

余生长醉 提交于 2019-12-12 02:00:06

问题


Folks, I have the following Class:

class User(object):
    def __init__(self, name, bd, phone, address):
        self.name = name
        self.bd = bd
        self.phone = phone
        self.address = address


myUser = User(name, bd, phone, address)

Now I need to store myUser as an object in MongoDB. Should I use jsondumps for this? Whats the proper way of converting this object for pymongo?

Thanks


回答1:


While using an ORM is a good approach in general, depending on the complexity of your system, it might be simpler to do everything "manually".

In your case, it can be simply done as:

class User(object):
    def __init__(self, name, bd, phone, address):
        self.name = name
        self.bd = bd
        self.phone = phone
        self.address = address

    def to_document(self):
        return dict(
            name = self.name,
            bd = self.bd,
            phone = self.phone,
            address = self.address,
        )

    @classmethod
    def from_document(cls, doc):
        return cls(
            name = doc['name'],
            bd = doc['bd'],
            phone = doc['phone'],
            address = doc['address'],
        )

You can also use the "shortcut" versions ...

def to_document(self):
    return self.__dict__
@classmethod
def from_document(cls, doc):
    return cls(**doc)

... though IMO explicit is better than implicit, and you'd pretty much have to switch to the "full manual version" as things get more complex (e.g. you might need to call one of the field's to_document if it's an object).




回答2:


You have multiple options:

  1. Store the user data as a dictionary and then dump in into json. It is doable, but I don't recommend it.

  2. Use ORM (Object Relation Mapper) which bascially maps an object (such as user) into a table in the database. The defacto ORM for Python is SQLAlchemy. However, since you mention MongoDB I suggest take a look at mongokit.



来源:https://stackoverflow.com/questions/24890979/python-convert-object-into-json-for-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!