在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
Book List List of Books
{% if books %} {% for book in books %} - Title: {{ book.title }}
Author: {{ book.author }}
Publication Date: {{ book.publication_date }}
Price: {{ book.price }}
{% endfor %}
{% else %} No books found.
{% endif %}
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'), ]
http://127.0.0.1:8000/app11/book_list_Q/