I have Blog
model below. *I use Django 3.2.16 and PostgreSQL:
# "store/models.py"
from django.db import models
class Blog(models.Model):
post = models.TextField()
def __str__(self):
return self.post
Then, store_blog
table has 2 rows below:
store_blog
table:
id | post |
---|---|
1 | Python is popular and simple. |
2 | Java is popular and complex. |
And, when running the filter()
code using |
or Q()
and |
or using or
or Q()
and or
in test()
view as shown below:
# "store/views.py"
from .models import Blog
from django.db.models import Q
from django.http import HttpResponse
def test(request):
# With "|"
# ↓ Here
qs = Blog.objects.filter(post__contains="popular") | \
Blog.objects.filter(post__contains="simple")
print(qs)
# With "Q()" and "|"
# ↓ Here # ↓ Here
qs = Blog.objects.filter(Q(post__contains="popular") |
Q(post__contains="simple"))
print(qs) # ↑ Here
# With "or"
# ↓ Here
qs = Blog.objects.filter(post__contains="popular") or \
Blog.objects.filter(post__contains="simple")
print(qs)
# With "Q()" and "or"
# ↓ Here # ↓ Here
qs = Blog.objects.filter(Q(post__contains="popular") or
Q(post__contains="simple"))
print(qs) # ↑ Here
return HttpResponse("Test")
|
or Q()
and |
can run OR
operators according to the query logs of PostgreSQL as shown below: