If you want to run raw queries in Django, you can easily do it with raw (). Reference: Performing raw SQL queries
models/users.py
import django.db from models
class Users(models.Model):
name = models.CharField()
age = models.IntegerField()
sex = models.CharField()
To get users over 40 years old in the users table
sql = "SELECT * FROM users WHERE age >= 40"
users = Users.objects.raw(sql)
The result is the same as below.
users = Users.objects.filter(age__gte=40)
You can also specify parameters and execute.
sql = "SELECT * FROM users WHERE age >= %s"
users = Users.objects.raw(sql, [40])
When specifying in dictionary type. In the above case, what is the value when there are multiple parameters? As it becomes difficult to understand, the following is recommended.
sql = "SELECT * FROM users WHERE age >= %(age)s AND sex = %(sex)s"
params = {"age": 40, "sex": "male"}
users = Users.objects.raw(sql, params)
Recommended Posts