1. gte: 代表的是大於等於,英文全稱為:great than equal。舉例:找到文章id大於等於3等文章,示例代碼如下:
定義模型的示例代碼如下:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
db_table = 'category'
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True)
def __str__(self):
return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content)
class Meta:
db_table = 'article'
views.py文件中視圖函數的示例代碼如下:
from .models import Article, Category
from django.http import HttpResponse
def index(request):
# gte:查找出文章id大於等於3的文章
articles = Article.objects.filter(id__gte=3)
print(articles)
print(articles.query)
return HttpResponse("success")
打印出結果:
<QuerySet [<Article: <(Article: id: 3,title: 鋼鐵是怎樣煉成的, content: 你好)>>,
<Article: <(Article: id: 4,title: 中國吸引力, content: 精彩極了)>>]>
原生sql語句為:SELECT article
.id
, article
.title
, article
.content
, article
.category_id
FROM article
WHERE article
.id
>= 3
2. gt:代表的是大於等於。舉例查找id大於3的文章,示例代碼如下:
from .models import Article, Category
from django.http import HttpResponse
def index(request):
articles = Article.objects.filter(id__gt=3)
print(articles)
print(articles.query)
return HttpResponse("success")
打印出結果:
<QuerySet [<Article: <(Article: id: 4,title: 中國吸引力, content: 精彩極了
)>>]>
原生sql語句:SELECT article
.id
, article
.title
, article
.content
, article
.category_id
FROM article
WHERE article
.id
> 3
3.lte: 代表的是小於等於,舉例查找id小於等於3的文章,示例代碼如下:
from .models import Article, Category
from django.http import HttpResponse
def index(request):
articles = Article.objects.filter(id__lte=3)
print(articles)
print(articles.query)
return HttpResponse("success")
打印出結果:
<QuerySet [<Article: <(Article: id: 1,title: Hello, content: 你好)>>,
<Article: <(Article: id: 2,title: Hello World, content: 大家好)>>,
<Article: <(Article: id: 3,title: 鋼鐵是怎樣煉成的, content: 你好)>>]>
SELECT article
.id
, article
.title
, article
.content
, article
.category_id
FROM article
WHERE article
.id
<= 3
4.lt: 代表的是小於。舉例查找id小於3的文章。示例代碼如下:
from .models import Article, Category
from django.http import HttpResponse
def index(request):
articles = Article.objects.filter(id__lt=3)
print(articles)
print(articles.query)
return HttpResponse("success")
打印出結果:
<QuerySet [<Article: <(Article: id: 1,title: Hello, content: 你好)>>, <Article: <(Article: id: 2,title: Hello World, content: 大家好)>>]>
SELECT article
.id
, article
.title
, article
.content
, article
.category_id
FROM article
WHERE article
.id
< 3