Django.fun

is there any way or package by which we can perform filters(searching) on custom raw sql query in django?

I read the below document : https://docs.djangoproject.com/en/3.2/topics/db/sql/

in model there are lots of filter lookup available like field__gt, field__lt, field__range, field__contains

but i want to use these into raw sql like suppose

query = SELECT * FROM customers WHERE customers.name like '%name%' and age < 30 and status IN ('active','pending')

Here :

  • customers.name like '%name%'
    name would be user input so i want to protect it from sql injection as well as filter it using % operator
  • age < 30 30 would be user input, and want to perform < > = also
  • IN ('active','pending') want to pass list of string using IN operator

is there any proper way/package available by which we can run raw sql preventing sql injection as well as filtering data using %, IN, <, >, = operators.

Answers: 1

Answered by Keoni Garner, Dec. 3, 2021, 4:44 p.m.

How about using the Django ORM? (This would be the proper way)

Customer.objects.filter(name__contains=“name”, age__lt=30, status__in=[‘active’, ‘pending’])

Assuming table/column names and models/fields match up, that will result in the exact query you’re looking for with all of the security you want. If you really need to execute a raw query, then @Rvector gave you the docs you need.