Django表达式F和Q

F表达式

F表达式是用来优化ORM操作数据库的。例如、我们要将公司所有员工的薪水都增加1000元,如果按照正常的流程,应该是先从数据库中提取所有的员工工资到Python内存中,然后使用Python代码在员工工资的基础上增加1000元,最后再保存到数据库中。这里面涉及的流程就是:受限要从数据库中提取数据到Python内存中,然后再Python内存中做完运算,之后再保存到数据库中。示例代码如下:

employees = temployee.objects.all()
for employee in employees:
    employee.salary += 1000
    employee.save()

而如果我们使用F表达式就可以优化这个流程,他可以不需要先把数据从数据库中提取出来,计算完成后再保存回去;而是直接执行SQL语句,将员工工资增加1000元。示例代码如下:

from django.db.models import F
Employee.object.update(salary=F("salary")+1000)

F表达式不会马上从数据库中获取数据,而是在生成SQL语句的时候,动态的获取传给F表达式的值。再比如我们要向获取作者中name和email相同的作者数据。如果不适用F表达式那么需要使用下面的代码来完成:

authors = Author.objects.all()
for author in authors:
    if author.name == author.email:
        print(author)

但是如果我们使用F表达式,一行代码就可以搞定。具体代码如下:

from django.db.models import F 
authors = Author.objects.filter(name=F("emial"))

Q表达式

如果要想获取所有价格高于100元,并且评分高于9.0以上评分的图书。我们可以通过夏敏的代码来实现:

books = Book.objects.filter(price__gte=100,rating__gte=9)

上面这个案例是一个并集查询,可以简单的通过传递过个条件进去来实现。但是如果想要实现一些复杂的查询语句,比如我们要查询所有价格低于10元,或者是评分低于9分的图书。那就没办法通过传递多个条件进行实现了。这个时候我们就需要适用Q表达式来实现了。具体代码如下:

from django.db.models import Q
books = Book.objects.filter(Q(price__lte=10) | Q(rating__lte=9))

上面进行的是或运算,当然还可以进行其他的运算,比如有 & 和 ~ (非)等。我们可以参考下面的一些Q表达式的例如:

from django.db.models import Q
# 获取id等于3的图书
books = Book.objects.filter(Q(id=3))

# 获取id等于3,或者名字中包含文字“记”的图书
books = Book.objects.filter(Q(id=3) | Q(name__contains("记")))

# 获取价格大于100,并且书名中包含“记”的图书
books = Book.objects.filter(Q(price__gte=100) & Q(name__contains("记")))

# 获取书名包含“记”,但是id不等于3的图书
books = Book.objects.filter(Q(name__contains("记")) & ~Q(id=3))

推荐文章

35条评论

  1. If some one desires to be updated with most up-to-date technologies therefore he must be visit this web page and be up to date everyday. Marjory Wainwright Varden

  2. I think that is among the such a lot vital information for me. Ardelle Bryce Toddie

  3. For most recent information you have to go to see web and on the web I found this web site as a most excellent web site for most recent updates. Liane Aldo Agathy

  4. Opportunities are now available in New Jersey. Get started today. Remy Cyrillus Darcee

  5. Good article! We will be linking to this particularly great content on our site. Keep up the great writing. Riane Pietrek Jegger

  6. Happy Faces We are up to standard with our products and services. We will meet your request and we hope that you leave us your testimony to encourage others. Vinnie Nickolas Tamara

  7. I have read so many articles about the blogger lovers however this paragraph is in fact a nice paragraph, keep it up. Tilly Haze Ori

  8. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast. Sonni Reuben Alix

  9. Everyone loves it when people get together and share views. Great site, stick with it! Orelle Robin Gavin

  10. Thanks for fantastic info I was looking for this info for my mission. Mellisa Jan Hilaria

  11. Very good article. I am going through some of these issues as well.. Madelina Joel Sergias

  12. Popcorn Time does not smack you with annoying ads wuen streaming films or TV exhibits. Teriann Vinny Silvester

  13. Excellent site. A lot of helpful info here. I am sending it to several buddies ans additionally sharing in delicious.
    And obviously, thanks to your effort!

  14. The article is really excellent. Every time I read it, I get information again.
    The best article I’ve read in a long time. Thank You…

  15. Really thank you for this beautiful article, it was a very informative article.

  16. The article is really excellent. Every time I read it, I get information again.
    The best article I’ve read in a long time. thankx

  17. Article is really excellent. Every time I read it,
    Really thank you for this beautiful article, it was a very informative articlee.

  18. The article is really excellent. Every time I read it, I get information again.
    The best article I’ve read in a long tiime……

  19. Just desire to say your article is as amazing. The clarity
    in your post is just cool and i can assume you are an expert on this subject
    Thanks a million and please keep up the enjoyable work.

  20. My relatives every time say that I am wasting my time here at net, however I
    know I am getting know-how all the time by reading thes
    good articles.

  21. Spot on with this write-up, I actually feel this
    website needs a great deal more attention. I’ll probably be returning to see
    more, thanks for the information!

  22. Pretty section of content. I just stumbled upon your weblog and
    in accession capital to assert that I acquire actually enjoyed account your blog
    posts. Anyway I’ll be subscribing to your augment and
    even I achievement you access consistently quickly

  23. Greetings! I know this is somewhat off topic but I was wondering if you knew
    where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding
    one? Thanks a lot.!

  24. My relatives every time say that I am wasting my time here at net, however I
    know I am getting know-how all the time by reading thes
    good articles.

  25. Pretty section of content. I just stumbled upon your weblog and
    in accession capital to assert that I acquire actually enjoyed account your blog
    posts. Anyway I’ll be subscribing to your augment and
    even I achievement you access consistently quickly

  26. Thank you for this beautiful article. It’s really a good article

  27. Hey! This is my 1st comment here so I just wanted to give
    a quick shout out and tell you I truly enjoy reading through your
    articles. Can you recommend any other blogs/websites/forums that deal
    with the same subjects? Thank you so much!

  28. Awesome blog you have here but I was wondering if you knew of any message
    boards that cover the same topics discussed in this article?
    I’d really like to be a part of community where
    I can get suggestions from other knowledgeable people that share the same interest.

    If you have any suggestions, please let me know. Appreciate it!

  29. I do not even know how I ended up here, but I thought this post was great.
    I do not know who you are but certainly you are going to a famous blogger if you are
    not already 😉 Cheers!

  30. Thanks for your marvelous posting! I genuinely enjoyed reading it, you are a great author.
    I will make certain to bookmark your blog and will often come back later on. I want
    to encourage you to definitely continue your great job,
    have a nice evening!

  31. you are best, verry nicee blog your amazing site.

  32. The article is really excellent. Every time I read it, I get information again.
    The best article I’ve read in a long time….

  33. your articles are very good and your blog sitee is really good

  34. Your articles and comments are really nice. Wwe wish you luck. good day.

发表评论

邮箱地址不会被公开。 必填项已用*标注