简体   繁体   English

if语句在hybrid_property表达式中

[英]if statement in a hybrid_property expression

I have a hybrid_property that performs some conditional and returns a response. 我有一个hybrid_property执行一些条件并返回一个响应。 I'd like to be able to query against this field so I've created an expression . 我希望能够查询这个字段,所以我创建了一个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 你可以使用case表达式

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
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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