我试图使用Pony ORM获取MySQL中的View返回的数据,但documentation没有提供有关如何实现此目的的任何信息(好吧,我找不到任何信息)解决方案,直到这一刻)。 Pony ORM能做到这一点吗?如果是这样,我该怎么办才能让它发挥作用?
这是我的MySQL视图:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `admin`@`%`
SQL SECURITY DEFINER
VIEW `ResidueCountByDate` AS
SELECT
CAST(`ph`.`DATE` AS DATE) AS `Date`,
COUNT(`art`.`RESIDUE_TYPE_ID`) AS `Aluminum Count`,
COUNT(`prt`.`RESIDUE_TYPE_ID`) AS `PET Count`
FROM
((((`TBL_PROCESS_HISTORY` `ph`
JOIN `TBL_RESIDUE` `pr` ON ((`ph`.`RESIDUE_ID` = `pr`.`RESIDUE_ID`)))
LEFT JOIN `TBL_RESIDUE_TYPE` `prt` ON (((`pr`.`RESIDUE_TYPE_ID` = `prt`.`RESIDUE_TYPE_ID`)
AND (`prt`.`DESCRIPTION` = 'PET'))))
JOIN `TBL_RESIDUE` `ar` ON ((`ph`.`RESIDUE_ID` = `ar`.`RESIDUE_ID`)))
LEFT JOIN `TBL_RESIDUE_TYPE` `art` ON (((`ar`.`RESIDUE_TYPE_ID` = `art`.`RESIDUE_TYPE_ID`)
AND (`art`.`DESCRIPTION` = 'ALUMINUM'))))
GROUP BY CAST(`ph`.`DATE` AS DATE)
ORDER BY CAST(`ph`.`DATE` AS DATE)
答案 0 :(得分:3)
您可以尝试以下方法之一:
1)定义一个新实体并将视图名称指定为该实体的表名:
class ResidueCountByDate(db.Entity):
dt = PrimaryKey(date, column='Date')
aluminum_count = Required(int, column='Aluminum Count')
pet_count = Required(int, column='PET Count')
之后,您可以使用该实体从视图中选择数据:
with db_session:
start_date = date(2017, 1, 1)
query = select(rc for rc in ResidueCountByDate if rc.date >= start_date)
for rc in query:
print(rc.date, rc.aluminum_count, rc.pet_count)
默认情况下,列名等于属性名。我为每个属性显式指定了列,因为在Python中,属性名称不能包含空格,通常用小写字母写。
如果表名不等于实体名,则可以显式指定表名:
class ResidueCount(db.Entity):
_table_ = 'ResidueCountByDate'
...
2)您可以编写原始SQL查询而无需定义任何实体:
with db_session:
start_date = date(2017, 1, 1)
rows = db.select('''
SELECT `Date` AS dt, `Aluminum Count` AS ac, `PET Count` AS pc
FROM `ResidueCountByDate`
WHERE `Date` >= $start_date
''')
for row in rows:
print(row[0], row[1], row[2])
print(row.dt, row.ac, row.pc) # the same as previous row
如果列名可以用作Python标识符(即它不包含空格或特殊字符),则可以使用点表示法访问列值,如上一行所示