[Answer]-Search criteria language parser in Python?

1👍

I’m not familiar with Django’s ecosystem, but the Python standard library contains ast.parse, which parses a valid Python expression string and produces an abstract syntax tree, which you can dissect and translate into a query – or a serie of function calls, or whatever you need. So if you can’t find anything more specific, then this might be of use.

This code:

ast.parse('donation_amount < 130 and donation_amount > 125')

returns the following AST structure:

ast.Module(
  ast.Expr([
    ast.BoolOp(ast.And(), [
      ast.Compare(
        [ast.Lt()],
        ast.Name('donation_amount', ast.Load()),
        [ast.Num(130)]),
      ast.Compare(
        [ast.Gt()],
        ast.Name('donation_amount', ast.Load()),
        [ast.Num(125)])])]))

So that takes care of the parsing, but you’ll still need to translate that into a query of your own. But it looks like you only need to handle a small number of node types:

BoolOp -> and, or
Compare -> ==, !=, >, <, >=, <=, in, not in
Name -> identifiers (column names, true/false/null, etc.)
Num -> numbers
Str -> strings

And perhaps ast.Call nodes, if you want to support database functions, and ast.Tuple or ast.List nodes, if you want to support IN functionality. If the AST contains any other node types you can reject it as an invalid query.

0👍

Do you use Django ORM to model the database? If so then wouldn’t it come down to:

 Donation.objects.filter(donation_amount__lte=130).filter(donation_amount__gte=125)

Leave a comment