1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoで簡単OR検索

Last updated at Posted at 2020-01-26

経緯

POSTリクエストからOR検索のクエリをつくりたい!
DjangoでOR検索をするのにQオブジェクトをパイプで繋いでクエリを作るのはマニュアルなどでパッとわかるが、POSTリクエストの内容からループで回したりして動的にQオブジェクトを作る方法が分らなかったので調査。

よくあるサンプルで目的に近いもの[1]

from functools import reduce
import operator
options = ['1', '2', '3', '4']

# uses operator or to combine the Q objects with the particular option filter
query = reduce(operator.or_, (Q(value__icontains=option) for option in options))

polls = Poll.objects.get(query)

これだとQ(value__icontains=option)valueが固定になってしまう。。。

今回作ったやつ

from functools import reduce
import operator

        queries = []
        for key_name, value in request.POST.dict().items():
            if not value and key_name != 'csrfmiddlewaretoken':
                queries += [Q((key_name+"__icontains", value))]
        res = Your_Model.objects.filter(reduce(operator.or_, queries))

※CSRF対策ちゃんとしてね

下から2行目のqueries +=の行の書式がパッと分らず苦労したわ。。。
同じことやりたい人が苦労しません様に( ˘ω˘)

参考:
[1] https://stackoverflow.com/questions/46970160/django-correct-way-to-convert-list-to-combined-or-for-q-object/46970411

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?