简体   繁体   中英

if statement in a hybrid_property expression

I have a hybrid_property that performs some conditional and returns a response. I'd like to be able to query against this field so I've created an expression . However, I'm unsure as to how to write a conditional for this sort of use case.

How do I write an expression that multiplies one of two fields against another based on the result of a conditional?

@hybrid_property
def func(self):
    if self.some_column is True:
        return self.true_column * self.amount
    return self.false_column * self.amount

@func.expression
def func(cls):
    # ???
    return

you can use case expression

from sqlalchemy import case

@func.expression
def func(cls):
    return case(
        [
            (cls.some_column == True, cls.true_column * cls.amount),
        ],
        else_=cls.false_column * cls.amount
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM