How to dynamically compose an OR query filter in Django?

后端 未结 14 1344
清歌不尽
清歌不尽 2021-01-22 05:24

From an example you can see a multiple OR query filter:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

For example, this results in:

14条回答
  •  后悔当初
    2021-01-22 06:19

    Another option I wasn't aware of until recently - QuerySet also overrides the &, |, ~, etc, operators. The other answers that OR Q objects are a better solution to this question, but for the sake of interest/argument, you can do:

    id_list = [1, 2, 3]
    q = Article.objects.filter(pk=id_list[0])
    for i in id_list[1:]:
        q |= Article.objects.filter(pk=i)
    

    str(q.query) will return one query with all the filters in the WHERE clause.

提交回复
热议问题