1

I know if it is very easy to add API filtering to a rest API in Django.

/api?name=joseph&age=5. # I already have that

however, I am using a react package to generate the query, and it generates SQL string as such:

"name = 'joseph' AND age = 5"

I wonder what would be the easiest way to filter a table with SQL-string. The query could be nested with ORs and ANDs and NOTs. Please help ..

1 Answer 1

2

Performing raw sql queries in django is way easy in terms of how would you perform.
Just you need to add raw in your queryset and perform the model building.


Below are the code snippet tor your reference

>>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
...
>>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
... 

Example as per your requirement :

name = 'joseph'
age = 5
sqlQuery = "SELECT * from <DBNAME> where name = "+name+" AND age = "+age
result = Person.objects.raw(sqlQuery)

# use of OR operator
name = 'joseph'
age = 5
result = Person.objects.filter(name=name) | Person.objects.filter(age=age) 

## use of AND operator
name = 'joseph'
age = 5
result = Person.objects.filter(name=name).filter(age=age) 

Your can read here for more

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

4 Comments

so do you recommend to use a "post" to send the query string to the API, and use the string as sqlQuery in "Person.objects.raw(sqlQuery)". since the other examples, you provided are hardcoded.
yes, it is better to send the params required as post request @JooJoo1020
would "Person.objects.raw(sqlQuery)" be smart enough to handle OR and AND and NOT ? so could the sqlQuery be something like "name = 'joseph' or age >5" ?
both are okay, try it out, which one are you comfortable go with it, i have stated all the available choices @JooJoo1020

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.