from django.db.models import F,Q # 1.查询库存数大于卖出数的书籍 res = models.Book.objects.filter(kucun__gt=F(‘maichu‘)) print(res) #<QuerySet [<Book: Book object>]> # 2.将所有书的价格提高100 models.Book.objects.update(price=F(‘price‘) + 100) """ 帮你获取到表中某个字段对应的值 """
Q查询
Q能够改变查询的条件关系 and or not
# 查询书的名字是python入门或者价格是1000的书籍 # res = models.Book.objects.filter(title=‘水浒传‘,price=1100) # and关系 # res = models.Book.objects.filter(Q(title=‘python入门‘),Q(price=1100)) # 逗号也是and关系 res = models.Book.objects.filter(Q(title=‘西游记‘)|Q(price=1100)) # |是or关系 # res = models.Book.objects.filter(~Q(title=‘水浒传‘)) # ~是not关系 print(res) print(res.query)
Q的高阶用法
q = Q() q.connector = ‘or‘ # q对象默认是and关系 可以通过connector改变or q.children.append((‘title‘,‘三国‘)) q.children.append((‘price‘,‘1100‘)) res = models.Book.objects.filter(q) print(res)
补充:
from django.db.models import F,Q F 针对自己单表中字段的比较和处理 models.Book.objects.filter(good__gt=F(‘comment‘)*2) models.Book.objects.all().update(price=F(‘price‘)+1) Q & | 非~ filter(Q(xx=11)|Q(ss=22)&Q(oo=33)) filter(Q(Q(xx=11)|Q(ss=22))&Q(oo=33)) &优先级高 filter(Q(Q(xx=11)|Q(ss=22))&Q(oo=33),name=‘dd‘) ``` 执行原生sql(了解) ``` models.Publish.objects.raw(‘原生sql‘) from django.db import connection cursor = connection.cursor() cursor.excute(sql,[1,]) cursor.fetchall() ``` 展示sql的 ``` models.Book.objects.filter(good__gt=F(‘comment‘)*2) from django.db import connection print(connection.queries) ```
https://www.cnblogs.com/clschao/articles/10439958.html