2016-03-02 46 views
0

我有時需要在不同的查詢中重用某個SQL表達式。如果表達式在所有情況下都查詢同一個表,那麼模型似乎是一個放置它的好地方。但是,我並不總是需要標量屬性,如果我不需要它,我不想實現它。SQLAlchemy - 將表達式附加到模型

這裏是我如何做到這一點:

@hybrid_property 
def some_property(self): 
    """Allows the query-level expression to exist.""" 
    raise NotImplemented 

@some_property.expression 
def some_property(cls): 
    """Query blah blah blah.""" 
    return case(
     ... snip ... 
    ).label('some_property') 

現在,標量實現不做任何事情(提高NotImplemented)。我怎樣才能避免寫它?

我不能作出這樣的表達一類屬性,因爲我需要參考在它的類,你不能指一類類級代碼:

class A(object): 
    c = A # NameError 

我理論上可以使它成爲一個類 - 但是沒有很好的實施。

我能想到的唯一選擇是在創建類並將其分配給類之後創建表達式。這是邪惡的。

回答

1

你就不能做到這一點:

@declared_attr 
def some_property(cls): 
    """Query blah blah blah.""" 
    return case(
     ... snip ... 
    ).label('some_property') 
1

你可以嘗試將其實現爲column property。列屬性就像只有表達式部分的混合屬性(這是你想要的,對吧?)。有一些限制,但對我來說這通常是有效的。使用deferred=true可以避免在不需要時進行評估。

some_property = column_property(
    select(**some column**).where(**some conditon**), 
    deferred=true 
)