Reputation: 95
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 ..
Upvotes: 1
Views: 769
Reputation: 1814
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
Upvotes: 2