使用 SQLAlchemy 查询空字符串或 Null

and*_*swb 2 python postgresql sqlalchemy flask flask-sqlalchemy

我对数据库设计和网页设计还很陌生,所以请耐心等待。

我有一个 Flask 应用程序,我需要使用 Flask-sqlalchemy 根据 url 中传递的参数在数据库中进行搜索,例如:

.../index?part_number=123*321$description1=&description2=TestText
Run Code Online (Sandbox Code Playgroud)

星号将被解释为一个或多个字符,** 将被解释为单个字符。所以我将用 % 和 _ 替换它们,并终止任何特殊字符。

我的问题是:在数据库中,有些字段将为空字符串,有些字段将为 Null。但我需要将它们都解释为空字符串,以便当 arg 为空或 * 时返回它们。

我知道我可以做一些类似的事情.like(part_number == None | part_number == '%')。但我只想在搜索字符串为 * 的情况下执行此操作,但是当我有 10 个不同的参数,全部与一起组合在一起时,如何以巧妙的方式执行此操作?

这是相关代码的片段和精简版本。我不太确定如何制作一个可以自行运行以进行测试的小程序。

filter_args = ['part_number', 'description1', 'description2']  # actual code has ~10 args
filters = dict()
for arg in filter_args:
  filter_str = request.args.get(arg, type=str, default='*')  # get filter arg from url

  filter_str = '*' if filter_str == '' else filter_str  # if the filter string is empty, search for all

  #  Replace * by % and ** by _ and terminate special chars
  filter_str = filter_str.replace('\\', '\\\\')
  filter_str = filter_str.replace('%', '\%')
  filter_str = filter_str.replace('_', '\_')
  filter_str = filter_str.replace('**', '_')
  filter_str = filter_str.replace('*', '%')
  filters[filter_name] = filter_str

parts = Part.query.filter(
  Part.part_number.ilike(filters['part_number']),  # and
  Part.description1.ilike(filters['description1']),  # and
  Part.description2.ilike(filters['description2'])
).order_by(Part.part_number)
Run Code Online (Sandbox Code Playgroud)

Ed *_*net 5

当我遇到这个问题时,我正在寻找一种过滤空字符串或空字符串的方法。虽然 Ilja 的答案对于 OP 问题的具体情况是正确的,但我想我应该补充一点,合并功能也适用于我的情况。如果OP正在查找part_number为None或空的行:

Pat.query.filter(func.coalesce(Part.part_number, '') == '')
Run Code Online (Sandbox Code Playgroud)