2
我有这些类:动态生成的查询集
class Keyword(models.Model):
keyword = models.CharField(max_length=100, unique=True)
class Snippet(models.Model):
keywords = models.ManyToManyField(Keyword)
和搜索关键字的列表:
searchlist = ['Photo','Cat']
我想动态查询同时包含(和运行)片段的数据库关键字searchlist
。
从该片段列表中,返回每个片段中唯一关键字的列表,不包括原始搜索字词。
到目前为止,我有这样的:
# 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_keywords
是在snippet_list
所有关键字。而final_list
是combined_keywords
的有序独特版本。
什么意思是无法检索组合列表?该代码实际上看起来相当不错。 – sapi 2014-11-01 23:10:51
我已经添加了一个编辑来进一步解释它,谢谢。 – KylePennington11 2014-11-01 23:34:07
'final_list = list(set(sorted_keyword_list)| set(combined_keywords))'诀窍? – Soravux 2014-11-01 23:37:11