django-F对象、Q对象



应用场景(F标记字段而非取值)

资源竞争的情况,F对象可以解决并发问题

image

image

字段之间的比较

image

In [1]: from bookstore.models import Book

In [2]: from django.db.models import F

In [3]: book=Book.objects.filter(market_price__gt=F('price'))

In [4]: for i in book:
   ...:     print(i.title)
   ...:
Django
JQury
HTML5

In [5]: book
Out[5]: <QuerySet [<Book: Django_清华大学出版社_1.00_85.00>, <Book: JQury_机械工业出版社_90.00_95.00>, <Book: HTML5_清华大学出版社_1.00_115.00>]>

Q对象

image

image

In [7]: from django.db.models import Q

In [8]: book=Book.objects.filter(Q(price__gt=20)|Q(pub='中信出版社'))

In [9]: book
Out[9]: <QuerySet [<Book: JQury_机械工业出版社_90.00_95.00>, <Book: Linux_机械工业出版社_80.00_75.00>]>

In [10]: book=Book.objects.filter(Q(price__gt=20)|Q(pub='清华大学出版社'))

In [11]: book
Out[11]: <QuerySet [<Book: Django_清华大学出版社_1.00_85.00>, <Book: JQury_机械工业出版社_90.00_95.00>, <Book: Linux_机 械工业出版社_80.00_75.00>, <Book: HTML5_清华大学出版社_1.00_115.00>]>

In [12]: for i in book:
    ...:     print(i.price)
    ...:
1.00
90.00
80.00
1.00
posted @ 2021-08-12 10:05  yescarf  阅读(66)  评论(0编辑  收藏  举报