Django之F与Q查询

F查询

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)