当数据库中有post时,为什么返回None

2024-03-28 03:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是显示博客包含的评论/帖子的数量。我已经编写了从数据库获取的代码,将由self.comment\编号。不过,虽然博客上有明显的帖子,self.comment\编号返回无。你知道吗

Python代码

class Blog(object):
    def __init__(self, author, description, author_id, _id=None, comment_num=None):
        self.author = author
        self.author_id = author_id
        self.description = description
        self._id = uuid.uuid4().hex if _id is None else _id
        self.comment_num = Database.count(collection='posts', query={'blog_id': self._id}) if comment_num is None else comment_num

    def json(self):
        return {
            'author': self.author,
            'author_id': self.author_id,
            'description': self.description,
            'comment_num': self.comment_num,
            '_id': self._id
        }

每个Post对象都包含一个与blog对象id相同的blog_id,因此database.count。你知道吗

你知道吗数据库.py文件

class Database(object):
    URI = os.environ.get("MONGOLAB_URI")
    DATABASE = None

    @staticmethod
    def initialize():
        client = pymongo.MongoClient(Database.URI)
        Database.DATABASE = client.get_default_database()

    @staticmethod
    def insert(collection, data):
        Database.DATABASE[collection].insert(data)

    @staticmethod
    def delete_one(collection, query):
        return Database.DATABASE[collection].delete_one(query)

    @staticmethod
    def find(collection, query):
        return Database.DATABASE[collection].find(query)

    @staticmethod
    def find_one(collection, query):
        return Database.DATABASE[collection].find_one(query)

    @staticmethod
    def update(collection, query, data):
        Database.DATABASE[collection].update(query, data, upsert=True)

    @staticmethod
    def count(collection, query):
        Database.DATABASE[collection].count(query)

我调用了count函数并提供了一个收集和查询。你知道吗

Blog对象,如数据库中所示。你知道吗

{
    "_id": "a6d836d23f524f21becbcf85c54dca90",
    "author": "Jongbin1010@gmail.com",
    "author_id": "09e116fa1a4a41aa8ec272f28809860b",
    "description": "Hello",
    "comment_num": null
}

Post对象。post对象的blog\u id与blog对象的\u id匹配

{
    "_id": "812e2e1725604e899af0c4484d7209e6",
    "blog_id": "a6d836d23f524f21becbcf85c54dca90",
    "author": "Jongbin1010@gmail.com",
    "content": "boy",
    "upvotes": 1,
    "created_date": {
        "$date": "2017-07-31T05:29:33.034Z"
    }
}

Tags: 对象selfnoneiddefcommentblogdescription