簡體   English   中英

如何創建一個包含 split() 的 hybrid_property?

[英]How to create a hybrid_property that incorporates split()?

鑒於簡單的表:

class Result(Base):
    __tablename__ = "result"

    id_ = Column(Integer, primary_key=True, autoincrement=True)
    result = Column(String(20))

result記錄的格式為6-17-5等。

我想創建一個對result字段中的整數求和的屬性,例如6-1將是7 我嘗試了以下方法:

@hybrid_property
def sum_games(self):
    return sum(int(s) for s in self.result.split("-"))

但我收到錯誤:

Exception has occurred: AttributeError
Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Result.result has an attribute 'split'

我對 Python 的了解足以讓self.result不是字符串,所以我不能使用split()方法。 有沒有辦法將其轉換為字符串? 我試過str(self.result)但它返回Result.result

也許還有另一種方法可以實現我正在尋找的輸出?

值得一提的是, result字符串實際上比上面的例子稍微復雜一些,但我總是需要split()方法,所以我已經簡化了這篇文章。

混合屬性有兩部分,Python 部分和 SQL 部分,用裝飾器@sum_games.expression 如果您不指定該expression對應項,則混合屬性本身也會在 SQL 中使用。 但是.split()和所有其他 python 函數在那里是未知的,所以請嘗試以下操作:

@hybrid_property
def sum_games(self):
    return sum(int(s) for s in self.result.split("-"))

@sum_games.expression
def sum_games(cls):  # yes this is a class method for some reason
    sum_part_array = func.regexp_split_to_array(cls.result, '-')
    sum_parts = func.unnest(sum_part_array).alias("y")
    sum_clause = func.sum(cast(column("y"), Integer)

    return select([sum_clause]).select_from(sum_parts).as_scalar()

與轉換為 SQL:

SELECT (SELECT SUM(y::int) FROM unnest(regexp_split_to_array(x, '-')) as y)
FROM (values ('6-1'), ('7-1')) as bla(x)

這適用於 PostgreSQL,如果您使用不同的方言,則相同的邏輯應該適用於等效的功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM