我正在嘗試為 a 的宣告性映射類設定一個 SQLAlchemy 混合屬性,該類Person具有一個DateTime稱為birth_date該人的出生日期的欄位。
我想設定一個@hybrid_property代表人的年齡,如下所示:
class Person(Base):
__tablename__ = 'person'
name: str = Column(String)
date_of_birth: DateTime = Column(DateTime)
#works fine after the objects are loaded
@hybrid_property
def age(self):
today = date.today()
if self.date_of_birth:
return today.year - self.date_of_birth.year - (
(today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
@age.expression
def age(cls): #Don't know how to set this up
pass
我在expression為混合屬性設定 時遇到問題。據我了解,該運算式應回傳一個 SQL 陳述句,該陳述句將有助于過濾/查詢資料庫中的人員年齡。
為此,以下 SQL 有效
SELECT (strftime('%Y', 'now') - strftime('%Y', person.date_of_birth)) - (strftime('%m-%d', 'now') < strftime('%m-%d', person.date_of_birth)) as age from person
但我不知道如何“告訴”運算式使用此 SQL(或者即使這是解決此問題的正確方法。)我嘗試使用這樣的文本:
@age.expression
def age(cls):
current_time = datetime.utcnow()
return text(f"{current_time.year} - strftime('%Y', '{cls.date_of_birth}')")
但它沒有用。我不知道如何告訴運算式使用 SQL 陳述句作為虛擬列的選擇。(那將是年齡列)
目標是能夠age像這樣過濾和查詢屬性:
session.query(Person).filter(Person.age > 25)
請提供幫助。
uj5u.com熱心網友回復:
混合屬性的那部分需要回傳一個可執行的 SQLAlchemy 子句。由于 Postgres 已經有一個合適的函式,你可以使用它:
import sqlalchemy as sa
@age.expression
def age(cls):
return sa.func.age(cls.date_of_birth)
功能:docs,查找age(timestamp).
或者在MySQL 中:
@age.expression
def age(cls):
return sa.func.timestampdiff('year', cls.date_of_birth, sa.func.curdate())
或者在 SQLite 中:
@age.expression
def age(cls):
strftime = sa.func.strftime
year_diff = strftime('%Y', 'now') - strftime('%Y', cls.date_of_birth)
# If the month and date of the current year are before the
# month and date of birth, then we need to subtract one year
# because the "birthday" hasn't happened yet.
is_partial_year = strftime('%m-%d', 'now') < strftime('%m-%d', cls.date_of_birth)
return year_diff - is_partial_year
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385859.html
上一篇:Windows:如何為PHP安裝或激活SQLite3
下一篇:SQLgroupby組內
