赞
踩
在Django中,Q()函数是一个非常有用的工具,主要用于构建复杂的查询。它允许你创建复杂的查询语句,包括AND、OR和NOT逻辑操作。这对于处理复杂的数据库查询特别有用,特别是在你需要组合多个条件或处理复杂的过滤逻辑时。
Q对象允许你使用关键字参数或Q对象的组合来构建查询。Q对象可以被链接在一起,使用
&
表示AND,
|
表示OR,
~
表示NOT。
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
Test/app11/views.py
- from django.shortcuts import render
- from django.db.models import Q
-
- def book_list_Q(request):
-
-
- # 1. 查询所有标题包含"Python"的书籍
- # books = Book.objects.filter(Q(title__icontains='Python'))
-
- # 2. 查询所有作者为"John Doe"的书籍
- # books = Book.objects.filter(Q(author='John Doe'))
-
- # 3. 查询所有在2020年之后出版的书籍
- # books = Book.objects.filter(Q(publication_date__year__gt=2020))
-
- # 4. 查询所有价格在20到30之间的书籍
- # books = Book.objects.filter(Q(price__gte=20) & Q(price__lte=30))
-
- # 5. 查询所有标题包含"Python"或作者为"John Doe"的书籍
- # books = Book.objects.filter(Q(title__icontains='Python') | Q(author='John Doe'))
-
- # 6. 查询所有标题包含"Python"且价格在20到30之间的书籍
- # books = Book.objects.filter(Q(title__icontains='Python') & Q(price__gte=20) & Q(price__lte=30))
-
- # 7. 查询所有不在2020年出版的书籍
- books = Book.objects.filter(~Q(publication_date__year=2020))
-
- return render(request, '11/book_list.html', {'books': books})
Test/templates/11/book_list.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Book List</title>
- </head>
- <body>
- <h1>List of Books</h1>
- {% if books %}
- <ul>
- {% for book in books %}
- <li>
- <strong>Title:</strong> {{ book.title }}<br>
- <strong>Author:</strong> {{ book.author }}<br>
- <strong>Publication Date:</strong> {{ book.publication_date }}<br>
- <strong>Price:</strong> {{ book.price }}<br>
- </li>
- {% endfor %}
- </ul>
- {% else %}
- <p>No books found.</p>
- {% endif %}
- </body>
- </html>
Test/app11/urls.py
- from django.urls import path
- from . import views
-
- urlpatterns = [
-
- path('book_list_Q/', views.book_list_Q, name='book_list_Q'),
- ]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。