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
解决方案
健康)状况
(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)
推荐阅读
- scala - Scala - 循环案例类名称以用作类型参数
- docker - Docker 集群 Kafka。如何为代理分配唯一主机
- http - Python中HTTPException和HTTP_404_NOT_FOUND的区别
- node.js - 在NodeJs中解析具有标题行格式的文件的最佳方法是什么
- javascript - 如何使用选择属性更改 TextField 的 MUI 菜单弹出框的背景颜色?
- google-sheets-api - 谷歌电子表格获取单元格颜色
- javascript - 如何访问 Promise 对象?
- php - 未定义的类常量“JSON_ARRAY”
- restructuredtext - 重组文本表和嵌入替换
- python - 删除包含特定字符串的行