如何仅在满足其他条件时按列筛选查询

2024-05-13 06:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题:

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

Tags: selfiddateifsiteusageinvoicefilter
1条回答
网友
1楼 · 发布于 2024-05-13 06:11:35

状况

(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)

相关问题 更多 >