2

I have a text area that lets a user build their own string which may look like any mix of AND OR NOT between words

ex:

"'disease' AND 'chemical' OR 'toxic' NOT 'imflammation' AND ('foo' OR 'bar')"

They are able to add words from a list, can click the appropriate button to add the AND OR NOT, and add parenthesis. So a string like that is what will be passed from my javascript to Django for me to parse/format to make a query. I can't find much about building a Django query that will handle boolean queries like that though. I don't really know where to start. I'm running MySQL on the backend too. Thanks for any help!

edit: the table I'm querying has a text column and the search will be directed at that. I'm trying to avoid doing a raw sql search in Django. I'm currently searching for things that can either convert any MySQL query to the appropriate Django query or ways to take a string and build a Django query directly from the string (the parenthesis are the hard part I think).

1

2 Answers 2

2

I assume that you have a set values stored in database, which are boolean values. If so, take a look at pyparsing. You could use simple string substitution to make the query parsable and build an expression. Then you can substitute variables with values fetched from database and evaluate it.

from sympy.parsing.sympy_parser import parse_expr
from sympy import symbols

# define all your symbols
A, B, C, D = symbols('A,B,C,D')
a, b, c, d = fetch_from_database()

user_expr_str = '(A & B) | C' # Change AND to &, OR to | and so on...
try:
    expr = parse_expr(user_expr_str)
except SyntaxError:
    # Do sth with error like return
# Evaluate the expression using data from DB
result = e.subs({A: a, B: b, C: c, D: d})

In the last line you can put all values, not only the ones used in expression.

Worth to mention, building query from user input could expose you to SQL injections and this solution is free of such danger.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you mean are the items I am searching for boolean values? I have an extremely large database and I'm doing a string search for each word the user added to the string ex: "wordOne OR wordTwo AND wordThree" and returning a string. I've expanded my original question to add more detail.
0

I found an answer in pyparsing and a script called simpleBool which let me send a string from my HTML textarea of the format from my question to Django and I was able to make Q objects that way. pyparsing is great and simpleBool helped a lot I suggest it for anyone looking to dynamically build queries which may consist of nested queries.

1 Comment

The link does not exist anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.