在 Django 中,如何从列表中构建一组条件?

In Django, how can I build a set of criteria from a list?

我正在使用 Python 3.7 和 Django。有没有一种方法可以重写下面的内容,所以我只执行一个查询而不是一堆查询?

def get_articles_with_words_in_titles(self, long_words):
    result = {}
    for word in long_words:
        qset = Article.objects.filter(title__icontains=word.lower())
        result.extend( qset )
    return result

我想获取至少包含其中一个单词的 Article 对象的唯一列表。

您可以使用 Q Objects. They are extremely useful allowing you to chain queries together. Along with functools’s reduce makes it so you can chain a series of Q objects together. reduce takes two arguments the first is the operator in our case we are using an or same as: | the second is the series. reduce then puts the operator between each element. More info on reduce and similar functions can be found here 完成此操作。

from functools import reduce
import operator
from django.db.models import Q

def get_articles_with_words_in_titles(self, long_words):
result = {}
    q_list = [Q(title__icontains=word) for word in long_words]
    qset = Article.objects.filter(reduce(operator.or_, q_list)
    result.extend( qset )
    return result

这个博客post也很有帮助using Q objects

是的,您可以像这样使用这些库对其进行迭代:

from functools import reduce   
from django.db.models import Q
import operator

qset = Article.objects.filter(reduce(operator.or_, (Q(title__icontains=x) for x in long_words)))