1 F Expressions

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

1.1 models结构

django F expressions 和Q objects_第1张图片

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
django F expressions 和Q objects_第2张图片


>>> 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导致的异常

django F expressions 和Q objects_第3张图片

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',
)