【问题标题】:How to filter a query by columns only if another condition is met仅在满足另一个条件时如何按列过滤查询
【发布时间】:2021-07-14 07:39:28
【问题描述】:

我有一个问题:

query = Usage.query.filter_by(site_id=self.site_id, invoice_num=self.invoice_num, supply_charge=self.supply_charge)

想要按日期过滤:

.filter(Usage.start_date>four_months_ago)

仅当被过滤的行具有相同的值时:

if subtotal == self.subtotal

有没有比创建 for 循环更好的方法?看起来效率很低。

for row in query.all():
    if self.start_date > four_months_ago:
        if row.subtotal != self.subtotal:
            del row

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    条件

    (subtotal == self.subtotal) & (Usage.start_date > four_months_ago)
    

    看起来像

    WHERE start_date > 'val1' AND subtotal = val2
    

    否则,OR subtotal != val2。您可以尝试使用or_ + and_。只是一个例子:

    subtotal = 1
    for user in Usage.query.filter(
        Usage.site_id == 2,
        Usage.invoice_num == 3,
        Usage.supply_charge == 4,
        or_(
            and_(Usage.start_date > for_month_ago, Usage.subtotal == subtotal),
            Usage.subtotal != subtotal,
        )
    ):
        print(user)
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2023-02-11
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多