2017-07-31 12 views
-1

私の目的は、ブログに含まれるコメント/投稿の数を表示することです。私はデータベースから取得するコードを書いており、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オブジェクトは、ブログ・オブジェクトIDと同じであるblog_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がNoneの場合else comment_num – Exprator

+0

コメントと投稿が異なる – ewwink

答えて

0

countの_idは、実際には他の方法とは異なり、値を返しません。

+0

カウントメソッドには** return **キーワードがありません。 – Nabin

関連する問題