sqlalchemy,混合属性案例陈述人

2024-04-25 08:01:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我试图通过sqlalchemy生成的查询

SELECT "order".id AS "id", 
"order".created_at AS "created_at", 
"order".updated_at AS "updated_at", 
CASE 
WHEN box.order_id IS NULL THEN "special" 
ELSE "regular" AS "type"
FROM "order" LEFT OUTER JOIN box ON "order".id = box.order_id

遵循sqlalchemy的文档,我尝试使用hybrid_属性来实现这一点。这就是我目前所掌握的,我没有得到正确的陈述。它没有正确生成case语句。在

^{pr2}$

Tags: boxidsqlalchemyisasorderselectnull
1条回答
网友
1楼 · 发布于 2024-04-25 08:01:48

对于非平凡表达式,hybrid属性必须包含两部分:Python getter和SQL表达式。在本例中,Python端是if语句,SQL端是case expression。在

from sqlalchemy import case
from sqlalchemy.ext.hybrid import hybrid_property


@hybrid_property
def type(self):
    return 'special' if self.order_type else 'regular'

@type.expression
def type(cls):
    return case({True: 'special', False: 'regular'}, cls.order_type)

相关问题 更多 >