django F expressions 和Q objects

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django F expressions 和Q objects相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

django中的F和Q

Django之F和Q查询

Django ORM F查询和Q查询

使用 F 和 Q 表达式进行 Django 模型过滤

Django ORM的F Q和extra操作

django操作数据库之查询F,Q操作 和 seach搜索功能