2017-07-31 50 views
-1

我的目標是顯示博客包含的評論/帖子的數量。我編寫了從數據庫獲取的代碼,並將由self.comment_num調用。但是,儘管博客中顯然有帖子,但self.comment_num返回無。當數據庫中有帖子時,爲什麼這會返回一個無

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) 

我叫計數功能,並提供了收集和查詢。

博客對象如數據庫中所示。

{ 
    "_id": "a6d836d23f524f21becbcf85c54dca90", 
    "author": "[email protected]", 
    "author_id": "09e116fa1a4a41aa8ec272f28809860b", 
    "description": "Hello", 
    "comment_num": null 
} 

發佈對象。後對象的blog_id的博客對象

{ 
    "_id": "812e2e1725604e899af0c4484d7209e6", 
    "blog_id": "a6d836d23f524f21becbcf85c54dca90", 
    "author": "[email protected]", 
    "content": "boy", 
    "upvotes": 1, 
    "created_date": { 
     "$date": "2017-07-31T05:29:33.034Z" 
    } 
} 
+0

你能告訴你如何創建Blog類的實例嗎? –

+0

是這條評論?如果comment_num是無其他comment_num – Exprator

+0

評論和帖子是不同的 – ewwink

回答

0

count的_id匹配實際上沒有返回值,不像其他方法。

+0

你的意思是,計數方法沒有** return **關鍵字? – Nabin

相關問題