1. 程式人生 > >django F expressions 和Q objects

django F expressions 和Q objects

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