Skip to content

Commit f9e5c2b

Browse files
committed
How to write SQL-like Query in Django ORM
1 parent 50fa55d commit f9e5c2b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
title : How to write SQL-like Query in Django ORM
3+
sidebar_label : SQL-like Query
4+
slug : how-to-write-sql-like-query-in-django-orm
5+
---
6+
7+
# How to write SQL-like Query in Django ORM
8+
9+
<SubHeading>Learn how to use Django ORM via SQL-like Queries</SubHeading>
10+
11+
In Django, you can use the `__icontains` lookup to perform a SQL `LIKE` query to filter results based on a substring match.
12+
This lookup allows you to search for records that contain a specific string anywhere within a text field.
13+
14+
![How to write SQL-like Query in Django ORM - Tutorial provided by AppSeed.](https://user-images.githubusercontent.com/51070104/268675023-54ea4ace-a8ad-442b-9b43-2ba12a6403ba.jpg)
15+
16+
> Here's how you can write a SQL `LIKE` query using Django ORM:
17+
18+
Assuming you have a Django model called `MyModel` and you want to perform a `LIKE` query on the `field_name` field:
19+
20+
```python
21+
from myapp.models import MyModel
22+
23+
# Use the __icontains lookup to perform a SQL LIKE query
24+
results = MyModel.objects.filter(field_name__icontains='search_term')
25+
```
26+
27+
In the code above:
28+
29+
- `MyModel` is your Django model.
30+
- `field_name` is the name of the field you want to search within.
31+
- `'search_term'` is the substring you want to search for.
32+
33+
The `filter` method returns a QuerySet containing all records that match the `field_name` containing the specified `search_term`.
34+
35+
The `__icontains` lookup performs a case-insensitive search, so it will match records regardless of the case of the `search_term`.
36+
37+
You can chain additional filters or query conditions to further refine your query. For example:
38+
39+
```python
40+
results = MyModel.objects.filter(field_name__icontains='search_term', another_field=some_value)
41+
```
42+
43+
This query will return records where `field_name` contains the `search_term` and `another_field` is equal to `some_value`.
44+
45+
Remember to replace `MyModel`, `field_name`, `'search_term'`, and any other specific values with your actual model, field name, and search criteria.
46+
47+
## ✅ Resources
48+
49+
- 👉 Access [AppSeed](https://appseed.us/) and start your next project
50+
- 👉 [Deploy Projects on Aws, Azure and Digital Ocean](https://www.docs.deploypro.dev/) via **DeployPRO**
51+
- 👉 Create an amazing landing page with [Simpllo, an open-source site builder](https://www.simpllo.com/)
52+
- 👉 [Django App Generator](https://app-generator.dev/django/) - A 2nd generation App Builder

0 commit comments

Comments
 (0)