MongoEngine查询列表,其对象具有以列表中指定的前缀开头的属性 [英] MongoEngine query list for objects having properties starting with prefixes specified in a list
问题描述
我需要查询Mongo数据库以查找具有某些属性的元素,这些元素以列表中的任何前缀开头.现在,我有一段这样的代码:
I need to query Mongo database for elements that have a certain property beginning with any prefix in the list. Now I have a piece of code like this:
query = mymodel(terms__term__in=query_terms)
,这匹配在列表"terms"上具有项目的对象,该项目具有在列表"query_terms"上显式出现的StringField"term".我要实现的是让对象的列表"terms"上的项具有StringField"term",该字段以出现在列表"query_terms"上的任何前缀开头.是否可以在一个查询中执行此操作,而不必在数据库中存储"term"的每个可能的前缀? 下面的解决方案效果很好,但是现在我必须找到带有以列表中每个前缀开头的术语的对象.我改变了
and this matches objects that have an item on a list "terms" that has StringField "term" explicitly occurring on a list "query_terms". What I want to achieve is having objects that have an item on a list "terms" that has StringField "term" beginning with any prefix that occurs on a list "query_terms". Is it possible to do it in one query and without storing every possible prefix of "term" in database? Solution below works great but now I have to find objects with terms starting with every prefix on a list. I changed
query = reduce(lambda q1, q2: q1.__or__(q2),
map(lambda prefix: Q(terms__term__startswith=prefix)))
到
query = reduce(lambda q1, q2: q1.__and__(q2),
map(lambda prefix: Q(terms__term__startswith=prefix)))
但是这不起作用.我最终收到以下错误:
but this does not work. I end up getting the following error:
InvalidQueryError: Duplicate query conditions: terms__term__startswith
有什么想法吗?
推荐答案
如果您查询的是其值的术语,则可以过滤以前缀开头的值,如下所示:
If your querying a term for it's value, you can filter the values that begin with a perfix like so:
MyModel.objects.filter(terms__term__startswith='foo')
如果需要过滤多个前缀,则必须为此创建Q对象:
If you need to filter for multiple prefixes you'll have to create Q objects for that:
MyModel.objects.filter(Q(terms__term__startswith='foo') | Q(terms__term__startswith='bar'))
如果您需要动态创建查询:
If you need to create the query dynamically:
prefixes = ['foo', 'bar', 'baz']
query = reduce(lambda q1, q2: q1.__or__(q2),
map(lambda prefix: Q(terms__term__startswith=prefix), prefixes))
MyModel.objects.filter(query)
这篇关于MongoEngine查询列表,其对象具有以列表中指定的前缀开头的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!