I was trying to develop a search application where a user can search and for my system requirement I need to avoid ORM query when I try to write this following raw query
q = request.POST.get('searchData')
if q:
titleInfo = Item.objects.raw("""select * from item where title like '%%s%'""", [q])
It gives me this error
ValueError at /test
unsupported format character ''' (0x27) at index 41
And if I remove the quotation
"""select * from item where title like %%s%"""
It gives me the following error
ValueError at /test
incomplete format
Where my query is working fine in MySQL database
I solve the problem like this
q = request.POST.get('searchData')
query = '%'+q+'%'
if q:
titleInfo = Item.objects.raw("select * from item where title like %s", [query])
Related
I am switching from SQLite to MySQL and getting some problems with my Queries. At the moment i am trying to SELECT from a Table where the PackageName is like a variable from a Text Input in my GUI.
The Query looks like this:
test = self.ms.ExecQuery("SELECT PackageID,PackageName,ServiceFee,Cost,LatestChanges FROM Package WHERE PackageName=?", (self.search_entry.GetValue(),))
and my ExecQuery looks like this:
def ExecQuery(self, sql):
cur = self._Getconnect()
cur.execute(sql)
relist = cur.fetchall()
cur.close()
self.conn.close()
return relist
And the error i am getting:
TypeError: ExecQuery() takes 2 positional arguments but 3 were given
What do i need to change to get this running?
You have sql as the 2nd parameter in your ExecQuery, yet you are passing in a sql query as the 1st parameter:
test = self.ms.ExecQuery("SELECT PackageID,PackageName,ServiceFee,Cost,LatestChanges FROM Package WHERE PackageName=?", (self.search_entry.GetValue(),))
How would I go about using the django.db.models Q module to query multiple lines of input from a list of data using a <textarea> html input field? I can query single objects just fine using a normal html <input> field. I've tried using the same code as my input field, except when requesting the input data, I attempt to split the lines like so:
def search_list(request):
template = 'search_result.html'
query = request.GET.get('q').split('\n')
for each in query:
if each:
results = Product.objects.filter(Q(name__icontains=each))
This did not work of course. My code to query one line of data (that works) is like this:
def search(request):
template = 'search_result.html'
query = request.GET.get('q')
if query:
results = Product.objects.filter(Q(name__icontains=query))
I basically just want to search my database for a list of data users input into a list, and return all of those results with one query. Your help would be much appreciated. Thanks.
Based on your comments, you want to implement OR-logic for the given q string.
We can create such Q object by reduce-ing a list of Q objects that each specify a Q(name__icontains=...) constraint. We reduce this with a "logical or" (a pipe in Python |), like:
from django.db.models import Q
from functools import reduce
from operator import or_
def search_list(request):
template = 'search_result.html'
results = Product.objects.all()
error = None
query = request.GET.get('q')
if query:
query = query.split('\n')
else:
error = 'No query specified'
if query:
results = results.filter(
reduce(or_, (Q(name__icontains=itm.strip()) for itm in query))
)
elif not error:
error = 'Empty query'
some_context = {
'results' : results,
'error': error
}
return render(request, 'app/some_template.html', some_context)
Here we thus first check if q exists and is not the empty string. If that is the case, the error is 'No query specified'. In case there is a query, we split that query, next we check if there is at least one element in the query. If not, our error is 'Empty query' (note that this can not happen with an ordinary .split('\n'), but perhaps you postprocess the list, and for example remove the empty elements).
In case there are elements in query, we perform the reduce(..) function, and thus filter the Products.
Finally here we return a render(..)ed response with some_template.html, and a context that here contains the error, and the result.
how to show the full string of a query using SQLQuery. I tried to use getQueryString()
but it doesn't show the parameter values in the returned string.
any idea how to display the full query that will be executed on the MySQL DB server?
Query query = session.createSQLQuery(
"select * from stock s where s.stock_code = :stockCode")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
query.getQueryString();
// this will return "select * from stock s where s.stock_code = :stockCode"
// and I need "select * from stock s where s.stock_code = 7277"
You can enable logging of the following categories (using a log4j.properties file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
Refer this :
Hibernate show real SQL
How to print a query string with parameter values when using Hibernate
I am new to R and I am trying to do something that feels simple but cant get my code to work.
When I run my code (sqlQuery and which saves the data to a SQL database) it works fine with the database name but when I use an object as the database name instead of the actual name I get the following error -Error in if (errors) return(odbcGetErrMsg(channel)) else return(invisible(stat)) :argument is not interpretable as logical
The way I am using the object name in my R code is for example is select * from ",object,".dbo.tstTable The object dataBase is the date of every previous Friday.
StartCode(Server = "Server01",DB=dataBase,WH=FALSE) POLICYLIST <- sqlQuery(channel1," SELECT DISTINCT [POLICY_ID] FROM ",dataBase,".[dbo].[policy] ") StartCode(Server = "SERVER02",DB="DataQuality",WH=FALSE) sqlQuery(channel1,"drop table DQ1") sqlSave (channel1, POLICYLIST, "DQ1")
Finally figured out why my code was not working I changed my code to the below to make it work. I just needed to add paste. appologies for my stupid question!
StartCode(Server = "Server01",DB=dataBase,WH=FALSE) POLICYLIST <- sqlQuery(channel1, paste" SELECT DISTINCT [POLICY_ID] FROM ",dataBase,".[dbo].[policy] ")) StartCode(Server = "SERVER02",DB="DataQuality",WH=FALSE) sqlQuery(channel1,"drop table DQ1") sqlSave (channel1, POLICYLIST, "DQ1")
Is it possible to construct raw SQL queries in Django so that they accept a dynamic number of arguments? So for example say that I have the following url structure in my app:
/books/category/history/
/books/category/history/1800s/
For the first query, I'm looking for all books with the keyword 'history', and for the second, I'm looking for all books with the keyword 'history' AND the keyword '1800s'.
I currently have two separate queries for each of these:
keyword1 = 'history'
SELECT appname_book.name AS name FROM appname_book WHERE keyword=%s,[keyword1]
keyword1 = 'history'
keyword2 = '1800s'
SELECT appname_book.name AS name FROM appname_book WHERE keyword=%s AND keyword=%s,[keyword1, keyword2]
Anyone know of a cleaner and more efficient way to do this?
I'm using Django 1.3 and MySQL.
Thanks.
Why dont you use Django QuerySet, like this:
Book.objects.all().filter(keyword__in=['history','1800s']).values('name')
Another possible solution using RAW SQL, coud be:
keywords = []
SQL = 'SELECT appname_book.name AS name FROM appname_book WHERE 1=1 '
SQL += ' '.join(['AND keyword=%s' for _ in params])
Sure, you could do something like this to dynamically generate a raw SQL query
sql = 'SELECT id FROM table WHERE 1 = 1'
params = []
if 'description' in args.keys():
sql += ' AND description LIKE %s'
params.append('%'+args['description']+'%')
if 'is_active' in args.keys():
sql += ' AND is_active LIKE %s'
params.append(args['is_active'])
... you can put as many "ifs" you want to construct the query
with connections['default'].cursor() as cursor:
cursor.execute(sql, params)
This way would still be completely safe against SQL Injections vulnerability