2012-01-19 18 views
4

假設我有一個在sqlalchemy中定義的名爲Customer的類來表示客戶表。我想寫一個搜索方法,這樣......sqlalchemy在表上作爲classmethod的搜索功能?

results = Customer.search(query) 

將返回基於該方法的結果。我想把它作爲@classmethod嗎?

@classmethod 
def search(cls,query): 
    #do some stuff 
    return results 

我可以使用cls代替DBSession.query嗎?

DBSession.query(Customer).filter(...) 
cls.query(Customer).filter(...) 

回答

4

我剛剛寫了一些類似的代碼,以下this reference

class Users(Base): 
    __tablename__ = 'users' 

    @classmethod 
    def by_id(cls, userid): 
     return Session.query(Users).filter(Users.id==userid).first() 

因此,您的第一個問題的答案似乎是「是」。不知道第二個,因爲我沒有替換DBSession的CLS。

7

要使用

cls.query 

你必須指定一個query_property到模型類!

你可能想在其他模型類使用這個爲好,所以你可能想這樣做,你的模型中基類的地方在你model/__init__.py

Base.query = Session.query_property() 

然後,你可以簡單地寫:

cls.query.filter(...) 

請注意,您不再指定要查詢的對象,這是通過使用query_property機制自動完成的。