Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while using like statement in django raw sql

I have a raw sql query which is always giving error while executing. Here is my query

Users.objects.raw('select target, username from users where location like \'%s%%\' and date(modified) = \'2011-06-14\'',[location])

I am taking the location = 'BUILD'

Location values would be 'BUILD_A', 'BUILD_B','BUILD_C'.

When I am executing the raw sql, below is the error I am getting.

DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BUILD'%' and date(modified) = '2011-06-14'' at line 1")

In MySQL terms I need to execute the following query:

Select target, username from users where location like 'BUILD%' and target = '2011-06-14'

I have googled it but could not able to get it. Please some one help me

like image 847
vkrams Avatar asked Jun 16 '11 03:06

vkrams


People also ask

How use raw SQL query in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What is raw SQL?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.

Does Django use SQL?

Django officially supports five database management systems: PostgreSQL, MariaDB, MySQL, Oracle, and SQLite (Django, 2020).

How do I query in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...


1 Answers

I have solved my problem in this way.

location = location + '%'

users_list = Users.objects.raw('select target, username from users where location like %s and date(modified) = %s',tuple([location,date]))

The above statement executes perfectly without any error and I can able to render the results in template also.

like image 143
vkrams Avatar answered Oct 30 '22 22:10

vkrams