码迷,mamicode.com
首页 > 其他好文 > 详细

django F expressions 和Q objects

时间:2018-03-06 17:17:37      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:F   Q   django   

1 F Expressions

refer: https://docs.djangoproject.com/en/2.0/topics/db/queries/#using-f-expressions-in-filters

1.1 models结构

技术分享图片

1.2 value安全update

>>>from django.db.models import F
>>>Reporter.objects.all().update(stories_filed=F(‘stories_filed‘) + 1)

1.3 同表 two value compare
技术分享图片


>>> from django.db.models import F
>>> Entry.objects.filter(n_comments__gt=F(‘n_pingbacks‘))

>>> Entry.objects.filter(n_comments__gt=F(‘n_pingbacks‘) * 2)
>>> Entry.objects.filter(rating__lt=F(‘n_comments‘) + F(‘n_pingbacks‘))

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F(‘pub_date‘) + timedelta(days=3))

1.4 跨表 two value compare

>>> Entry.objects.filter(authors__name=F(‘blog__name‘))

1.5若用save导致的异常

技术分享图片

2 Complex lookups with Q objects
filter(condition_1, condition_2) 2者为and关系
fiter(xxx).exclude(xxxx)级联条件为and,若要用or等需要用Q

refer https://docs.djangoproject.com/en/2.0/topics/db/queries/#complex-lookups-with-q

Keyword argument queries – in filter(), etc. – are “AND”ed together. If you need to execute more complex queries (for example, queries with OR statements), you can use Q objects.

2.1 Q对象
用 & 或 | 连接起来的2个q对象,产生1个Q对象

Q(question__startswith=‘Who‘) | Q(question__startswith=‘What‘)

sql语句等效为

WHERE question LIKE ‘Who%‘ OR question LIKE ‘What%‘

2.2 取反

Q(question__startswith=‘Who‘) | ~Q(pub_date__year=2005)

2.3 多个Q对象

Poll.objects.get(
    Q(question__startswith=‘Who‘),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

等效为如下sql(逗号等效为and)

SELECT * from polls WHERE question LIKE ‘Who%‘
    AND (pub_date = ‘2005-05-02‘ OR pub_date = ‘2005-05-06‘)

2.4 Q条件需要放置在其他条件之前

# valid
Poll.objects.get(
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    question__startswith=‘Who‘,
)

django F expressions 和Q objects

标签:F   Q   django   

原文地址:http://blog.51cto.com/13606158/2083470

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!