[django] Realize Q query in orm under django

Preface: How does orm under django implement Q query

library table

# 需求: 查询价格大于112或者评论数小于100的书籍
 
from myapp import models
from django.http import JsonResponse
from django.db.models import Count,Q
 
models.Book.objects.filter(price__gt=112,comment__lt=100)  # 这个是and关系不是或or,不满足需求

models.Book.objects.filter(Q(price__gt=112)|Q(comment__lt=100))  # 与&  或| 非~

models.Book.objects.filter(Q(price__gt=112)|~Q(comment__lt=100) # 大于等于100


#  扩展 嵌套

models.Book.objects.filter(Q(Q(price__gt=112)|~Q(comment__lt=100)|Q(ID=1)) # 嵌套

models.Book.objects.filter(Q(Q(price__gt=112)|~Q(comment__lt=100)|Q(id=1),id=2) # 嵌套+组合并且  ,必须写在Q 后面

 
 

Guess you like

Origin blog.csdn.net/legend818/article/details/131091022