filter()方法 用于实现数据过滤功能,相当于sql语句中的where子句。
filter(字段名__exact=10) 或 filter(字段名=10) | 类似sql 中的 =10 |
filter(字段名__gt=10) | 类似SQL中的 >10 |
filter(price__lt=29.99) | 类似sql中的 <29.99 |
filter(字段名__gte=10, 字段名__lte=20) | 类似sql中的 >=10 and <=10 使用filter()方法获取所有价格在10到20之间的书籍 |
# books = Book.objects.filter(price__gte=10, price__lte=20) # __gte是“greater than or equal to”(大于等于)的缩写,__lte是“less than or equal to”(小于等于)的缩写。
# books = Book.objects.filter(price__gt=10) # 在Django的ORM(对象关系映射)查询中,__gt是过滤条件的一个特殊语法,用于表示“大于”(greater than)。
books = Book.objects.filter(price__lt=29.99) # __lt 是“less than”(小于)的缩写。
1,添加模型
Test/app11/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.title
2,添加视图函数
Test/app11/views.py
from django.shortcuts import render
from .models import Post
def index(request):
posts = Post.objects.all()
return render(request, '11/index.html', {'posts': posts})
# apps/books/views.py
from django.shortcuts import render
from .models import Book
def book_list_view(request):
# 使用filter()方法获取所有价格在10到20之间的书籍
books = Book.objects.filter(price__gte=10, price__lte=20)
return render(request, '11/book_list.html', {'books': books})
3,添加路由地址
Test/app11/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index, name='index'),
path('book_list_view/', views.book_list_view, name='book_list_view'),
]
4,执行迁移
python manage.py makemigrations app11
python manage.py migrate app11
5,创建示例数据
Test/create_books.py
import os
import django
# 设置Django环境,需要指定settings模块
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Test.settings")
django.setup()
from app11.models import Book
def create_books():
# 创建示例书籍
book1 = Book(title="Python编程", author="小强", publication_date="2022-01-01", price=15.99)
book2 = Book(title="Django Web开发", author="小龙", publication_date="2022-04-15", price=29.99)
book3 = Book(title="算法导论", author="小龙", publication_date="2024-07-20", price=19.99)
book4 = Book(title="java入门到弃坑", author="余胜军", publication_date="2019-02-20", price=39.99)
book5 = Book(title="c入门到弃坑", author="小龙", publication_date="2012-07-20", price=9.99)
book6 = Book(title="c++入门到弃坑", author="小6", publication_date="2024-02-20", price=13.99)
book7 = Book(title="python多线程入门", author="小6", publication_date="2025-02-20", price=49.99)
# 保存书籍到数据库
book1.save()
book2.save()
book3.save()
book4.save()
book5.save()
book6.save()
book7.save()
print("数据创建成功!")
if __name__ == "__main__":
create_books()
6,访问页面
http://127.0.0.1:8000/app11/book_list_view/
可以看到10到20块的书籍数据都展示出来了