我的目标是显示博客包含的评论/帖子数量。我编写了从数据库获取的代码,并将由self.comment_num调用。然而,尽管博客中有明显的帖子,但self.comment_num返回None。
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
,它与博客对象ID相同。因此database.count
。
Database.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对象的blog_id与博客对象的_id匹配
{
"_id": "812e2e1725604e899af0c4484d7209e6",
"blog_id": "a6d836d23f524f21becbcf85c54dca90",
"author": "Jongbin1010@gmail.com",
"content": "boy",
"upvotes": 1,
"created_date": {
"$date": "2017-07-31T05:29:33.034Z"
}
}
答案 0 :(得分:0)
count
实际上不会返回该值。