动态构建查询集

时间:2014-11-01 22:40:19

标签: django

我有这些课程:

class Keyword(models.Model):
    keyword = models.CharField(max_length=100, unique=True)


class Snippet(models.Model):
    keywords = models.ManyToManyField(Keyword)

以及搜索关键字列表:

searchlist = ['Photo','Cat']

我想动态查询数据库中是否包含searchlist中关键字(AND操作)的片段。

从该代码段列表中,返回每个代码段中唯一关键字的列表,不包括原始搜索字词。

到目前为止,我有这个:

# Turn list of values into list of Q objects
queries = [Q(keywords__keyword__exact=tag) for tag in searchlist]

# Take one Q object from the list
query = queries.pop()

# Or the Q object with the ones remaining in the list
for item in queries:
    query &= item

# Query the model
snippet_list = Snippet.objects.filter(query) 

返回所需的片段列表,但我不确定如何检索关键字的组合列表,或者是否有更有效的方法来实现最终结果。

编辑:

我想在snippet_list上实现以下伪代码:

for snippet in snippet_list:
    combined_keywords += snippet.keywords

ordered_keyword_list = getOrderedKeywords()        # <- I have this function already

final_list =  intersection(ordered_keyword_list, combined_keywords)

其中combined_keywordssnippet_list中的所有关键字。 final_listcombined_keywords的有序唯一版本。

1 个答案:

答案 0 :(得分:0)

最终的解决方案看起来像是@Soravux和@ Dave-Webb。我不确定这是否是最有效的方法,但它确实有效。

# Turn list of values into list of Q objects
queries = [Q(keywords__keyword__exact=tag) for tag in valueslist]

query = Q()
for item in queries:
    query &= item

# Query the model
snippet_list = Snippet.objects.filter(query)

combined_keywords = []
for snippet in snippet_list:
    combined_keywords += snippet.keywords.all()

ordered_keyword_list = Keyword.objects.all().annotate(count=Count('snippet')).order_by('-count')

final_list = [x for x in ordered_keyword_list if x in combined_keywords]