python convert object into json for mongodb

后端 未结 2 1164
臣服心动
臣服心动 2021-01-26 13:10

Folks, I have the following Class:

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


        
2条回答
  •  独厮守ぢ
    2021-01-26 13:31

    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).

提交回复
热议问题