How to dynamically compose an OR query filter in Django?

后端 未结 14 1536
清歌不尽
清歌不尽 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:11

    Maybe it's better to use sql IN statement.

    Article.objects.filter(id__in=[1, 2, 3])
    

    See queryset api reference.

    If you really need to make queries with dynamic logic, you can do something like this (ugly + not tested):

    query = Q(field=1)
    for cond in (2, 3):
        query = query | Q(field=cond)
    Article.objects.filter(query)
    

提交回复
热议问题