Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python sqlalchemy,混合属性案例语句_Python_Python 3.x_Sqlalchemy - Fatal编程技术网

Python sqlalchemy,混合属性案例语句

Python sqlalchemy,混合属性案例语句,python,python-3.x,sqlalchemy,Python,Python 3.x,Sqlalchemy,这就是我试图通过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 = bo

这就是我试图通过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语句

from sqlalchemy import (Integer, String, DateTime, ForeignKey, select, Column, create_engine)
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property

Base = declarative_base()
class Order(Base):
    __tablename__ = 'order'
    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    order_type = relationship("Box", backref='order')
    @hybrid_property
    def type(self):
        if not self.order_type:
            return 'regular'
        else:
            return 'special'

class Box(Base):
    __tablename__ = 'box'
    id = Column(Integer, primary_key=True)
    monthly_id = Column(Integer)
    order_id = Column(Integer, ForeignKey('order.id'))

stmt = select([Order.id, Order.created_at, Order.updated_at, Order.type]).\
    select_from(Order.__table__.outerjoin(Box.__table__))
print(str(stmt))

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

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)