[Django] How to get data by specifying SQL.

If you want to run raw queries in Django, you can easily do it with raw (). Reference: Performing raw SQL queries

Sample Model

models/users.py


import django.db from models
class Users(models.Model):
    name = models.CharField()
    age = models.IntegerField()
    sex = models.CharField()

Data acquisition by specifying SQL

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)

Specify parameters

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

[Django] How to get data by specifying SQL.
How to get started with Django
How to get article data using Qiita API
How to use loc / iloc / ix to get by specifying a column in CASTable
How to get multiple model objects randomly in Django
How to get more than 1000 data with SQLAlchemy + MySQLdb
Data acquired by Django releted
How to handle data frames
How to get an overview of your data in Pandas
How to start Apache by specifying httpd.conf with systemd (CentOS7, CentOS8)
[Introduction to Python] How to get data with the listdir function
[Python] How to FFT mp3 data
[Django] How to test Form [TDD]
How to read e-Stat subregion data
How to deal with imbalanced data
How to deal with imbalanced data
How to get the Python version
How to get started with Scrapy
How to get started with Python
How to reflect CSS in Django
How to Data Augmentation with PyTorch
How to write Django1.9 environment-independent wsgi.py
How to collect machine learning data
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to get and set the NTP server name by DHCP
django + nginx How to make images viewed only by logged-in users
Here's a brief summary of how to get started with Django
How to get the pixel value of the point from the satellite image by specifying the latitude and longitude
How to do arithmetic with Django template
Step notes to get started with django
[Python Kivy] How to get the file path by dragging and dropping
How to collect Twitter data without programming
How to get parent id with sqlalchemy
How to get rid of long comprehensions
How to check the version of Django
How to get IP when Tornado + nginx
How to delete expired sessions in Django
How to get a stacktrace in python
How to get colored output to the console
How to get a namespaced view name from a URL (path_info) in Django
How to use "deque" for Python data
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
How to handle time series data (implementation)
How to read problem data with paiza
How to get started with laravel (Linux)
How to make only one data register on the Django admin screen
How to sort by specifying a column in the Python Numpy array.
I'm addicted to the difference in how Flask and Django receive JSON data
[Introduction to Python] How to get the index of data with a for statement
How to create sample CSV data with hypothesis
[python] How to display list elements side by side
How to convert m4a acquired by iTunes to wav
Try using django-import-export to add csv data to django
I tried to get an image by scraping
[Django] How to resolve errors when installing mysqlclient
How to set Django DB to mongodb visual studio 2019
How to develop a cart app with Django
How to get results from id in Celery
How to run some script regularly in Django