How to dynamically compose an OR query filter in Django?

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

    This one is for dynamic pk list:

    pk_list = qs.values_list('pk', flat=True)  # i.e [] or [1, 2, 3]
    
    if len(pk_list) == 0:
        Article.objects.none()
    
    else:
        q = None
        for pk in pk_list:
            if q is None:
                q = Q(pk=pk)
            else:
                q = q | Q(pk=pk)
    
        Article.objects.filter(q)
    

提交回复
热议问题