简体   繁体   English

SQLAlchemy - 值和默认值之间的最小值/最大值

[英]SQLAlchemy - min/max between value and the default

I'm trying to prepare a hybrid expression for such python query:我正在尝试为此类 python 查询准备一个混合表达式:

(min(end_date, self.start.date()) - max(start_date, self.end.date())).days

Basically I want to calculate how many days from given period are between object's start and end.基本上我想计算给定时间段内对象的开始和结束之间的天数。 An easier example written with ints.一个用整数编写的更简单的例子。 Let's say we have an object with start and end set to 3 and 8. Given such values for input it should return:假设我们有一个 object,开始和结束设置为 3 和 8。给定这样的输入值,它应该返回:

  • 1, 10 - return 5 (distance between 3 and 8) 1、10 - 返回 5(3 和 8 之间的距离)
  • 5, 10 - return 3 (distance between 5 and 8) 5、10 - 返回 3(5 到 8 之间的距离)
  • 1, 6 - return 3 (distance between 3 and 6) 1、6 - 返回 3(3 和 6 之间的距离)
  • 5, 6 - return 1 (distance between 5 and 6) 5, 6 - 返回 1(5 和 6 之间的距离)

Is there any other way to write in in sqlalchemy other than giant case statement for each option?除了每个选项的巨大案例语句之外,还有其他方法可以在 sqlalchemy 中写入吗?

The answer to that was func.least and func.greatest .答案是func.leastfunc.greatest

The full code was:完整的代码是:

func.date_part(
    'day',
    func.least(end_date, cls.end) - func.greatest(start_date, cls.start)
)

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

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